3

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!

1
  • can you show your whole onsubmit code? Commented May 10, 2011 at 4:16

3 Answers 3

10

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('');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but I tried both with and without quotes, and JQuery still does not recognise the new value entered by the user.
2

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(''); 
  } 
});

Comments

2

The behavior you expect seems to only work on jQuery 1.2.6 or below (tested on fiddle).

All the other versions clear out the original value. This is most likely since [value=""] probably checks for the original property value rather than the current value.

I've setup a fiddle here that you can look at : http://jsfiddle.net/jomanlk/4PBTZ/ Just change the jquery version on it.

I suggest you use an each() call.

$('input:text').each(function(){
    if ($(this).val() == 'enter highlight')  {
        $(this).val('');
    }
});

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.