197

I can't find the right selector for:

<input maxlength="6" size="6" id="colorpickerField1" name="sitebg" value="#EEEEEE" type="text">

I want to change the value to = 000000. I need the selector to find the "name" not the id of the text input.

Shouldn't this work?:

$("text.sitebg").val("000000");

The presented solution does not work, what's the problem with this?

$.getJSON("http://www.mysitehere.org/wp-content/themes/ctr-theme/update_genform.php",function(data) {
    $("#form1").append(data.sitebg);
    $('input.sitebg').val('000000');
});

The JSON data is working correctly; the idea is to later pass the JSON values into the form input text values. But is not working :(

informatik01
  • 16,038
  • 10
  • 74
  • 104
Joricam
  • 2,329
  • 4
  • 18
  • 14

6 Answers6

395

no, you need to do something like:

$('input.sitebg').val('000000');

but you should really be using unique IDs if you can.

You can also get more specific, such as:

$('input[type=text].sitebg').val('000000');

EDIT:

do this to find your input based on the name attribute:

$('input[name=sitebg]').val('000000');
Jason
  • 51,583
  • 38
  • 133
  • 185
51

jQuery way to change value on text input field is:

$('#colorpickerField1').attr('value', '#000000')

this will change attribute value for the DOM element with ID #colorpickerField1 from #EEEEEE to #000000

Vladimir Kroz
  • 5,237
  • 6
  • 39
  • 50
32

Best practice is using the identify directly:

$('#id').val('xxx');

Dehli
  • 5,950
  • 5
  • 29
  • 44
MGE
  • 803
  • 2
  • 12
  • 22
19

When set the new value of element, you need call trigger change.

$('element').val(newValue).trigger('change');

Richelly Italo
  • 1,109
  • 10
  • 9
  • This fixed a problem for me where the change event handler was getting called twice; once with the new value and then again with [attr=val] – Peter Mghendi Dec 26 '19 at 08:32
3

Just adding to Jason's answer, the . selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.

e.g.

$('element[attr=val]')

Kashyap
  • 15,354
  • 13
  • 64
  • 103
Robert Ingrum
  • 234
  • 3
  • 14
0

jQuery change input text value using parent class

$('.form-submit input.submit').val('Johnny Bravo');
  • .form-submit is the parent class
  • Johnny Bravo is the text that you want to change
Dilan
  • 2,610
  • 7
  • 23
  • 33