1

I have this input field in html:

<input id="title" type="text" class="" />

A button will allow the user to randomize the value of the input field by calling a js function.

var title = document.getElementById("title");
title.removeAttribute("value");
title.setAttribute("value",random_name);

If the user wants to change the value auto-asigned by my function (aka random_name), he can simply type something else in the input field.

All works fine until now, however if the user changes his mind and clicks the randomize button again, the function is called and "value" attribute is modified, but the user still sees the last thing he typed and not the new random value.

Is there a way to fix this or maybe a workaround?

1
  • Instead of title.removeAttribute() and title.setAttribute() just assign to title.value directly. Commented May 16, 2014 at 15:14

2 Answers 2

1

Just do title.value = random_name

You can set an input's value by element.value = "desired_value". If you use that, it works.

http://jsfiddle.net/f4gVR/2/

<input id="title" type="text" class="" />
<input type="button" class="" onclick="randomValue()" value="Random" />

function randomValue() {
  var title = document.getElementById("title");
  title.value = Math.random(); // assign random_name to title.value here
}

if it's your random_name bugging out, you should post the code. Try this first. Just replace Math.random() with random_name.

Sign up to request clarification or add additional context in comments.

Comments

1

you need to use title.value = random_name; instead of title.setAttribute("value",random_name);

Fiddle: http://jsfiddle.net/4dhKa/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.