22

I need to remove some values from a hidden and text input box using jQuery, but somehow this is not working

Example:

<input type="hidden" value="abc" name="ht1" id="ht1" />
<input type="text" name="t1" id="t1" />

I use the following jQuery code to remove the values with an onclick event

$('#rt1').click(function() {
    $('#t1').val();  
    $('#ht1').val();  
});

Can I empty the contents of the input box and clear the value of the hidden field using jQuery?

6 Answers 6

43

You should do this:

$('#rt1').click(function() {
    $('#t1').val('');  
    $('#ht1').val('');  
});

That is, pass an empty string. Either that, or use removeAttr (query.removeAttr('value')).

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

2 Comments

+1, Seconded, I would say removeAttr() is the preferred way to do this.
Note that the attribute is NOT removed with .val(''), so if you have dependencies checking for the existence of the attribute (not the value), you do need to run removeAttr. (In my code I had dependencies on both, so I even had to run query.val('').change().removeAttr('value')).
27
$('#rt1').click(function() {
    $('#t1').attr('value', '');  
    $('#ht1').attr('value', '');  
});

2 Comments

Also you can shorten to $('#t1, #ht1').attr('value', '');
This does not seem to work in my case, while .val('') does.
9

Shorter version

$('#rt1').click(function() {
    $('#t1, #ht1').val('');  
});

Comments

5

You just need to pass an empty string in the val() function or, you can use the more generic attr() function that sets a given attribute to a given value:

$('#rt1').click(function() {
    $('#t1').attr("value", "");  
    $('#ht1').attr("value", "");  
});

1 Comment

This should work but in my case I don't know y it is not working so I used $('#t1').val(). It works fine for me. I don't why in my case .attr is not working. If any one explain this then it is good for us.
2

This should be:

$('#rt1').click(function() {
    $('#t1').val('');  
    $('#ht1').val('');  
});

When val() function doesn't have parameter it will serves as getter not setter

1 Comment

$('#t1').attr("value", ""); why this is not working for me, same place ur code is working. Can u explain please.
2
$(document).ready(function(){ 

  $('input').click(function(){ 

    $(this).removeAttr('value');

  });
});

//remove value when click

//without effect input type  submit 
$(document).ready(function(){ 

  $('input:not(:submit)').click(function(){ 

    $(this).removeAttr('value');
  });
});

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.