Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all input fields with a certain value using JQuery

Tags:

jquery

I have the following code that executes when a form submits:

$('input[value=enter highlight]').val('');

Essentially, it searches through the form for all text fields containing the value 'enter highlight' and removes that text. The problem is that when the HTML code for the text field is as follows:

<input type="text" value="enter highlight"/>

and the user manually changes this value in the form, JQuery still recognises the field's value as the original value that was set in the HTML code (i.e. 'enter highlight') and resets the field's value to blank, even though the user entered a different value into the field. Very unexpected behaviour.

Any idea what I need to do to make sure JQuery will take into account any changed values users entered into the text box before clearing the values?

Many thanks!

like image 597
Bug Magnet Avatar asked Sep 26 '26 18:09

Bug Magnet


2 Answers

Not sure if this is the problem, but your JQuery selector should have quotes in it

$('input[value="enter highlight"]').val('');

failing that, try this:

$('input[value="enter highlight"]').each(function () {
    if ($(this).val() == "enter highlight") $(this).val('');
});
like image 145
Andrew Cooper Avatar answered Sep 29 '26 10:09

Andrew Cooper


I vaguely remember reading that the selectors work off the values in the original HTML source, so don't pick up changes to the attribute values made after the DOM has loaded.

Changing it to an explicit loop should work, though it's less concise:

$('input').each(function() { 
  if($(this).val()=="enter highlight") { 
    $(this).val(''); 
  } 
});
like image 42
Tom Avatar answered Sep 29 '26 10:09

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!