Elitmiar
Elitmiar

Reputation: 36839

Remove value of input using jQuery

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?

Upvotes: 22

Views: 94512

Answers (6)

Indranil
Indranil

Reputation: 165

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

Upvotes: 2

dotty
dotty

Reputation: 41433

Shorter version

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

Upvotes: 8

jerjer
jerjer

Reputation: 8760

This should be:

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

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

Upvotes: 2

rogeriopvl
rogeriopvl

Reputation: 54056

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", "");  
});

Upvotes: 5

Tamas Czinege
Tamas Czinege

Reputation: 121294

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')).

Upvotes: 43

Mark Bell
Mark Bell

Reputation: 29735

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

Upvotes: 28

Related Questions