Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the Name attribute of an input field using Jquery?

Quick question... I was wondering how I can get this to happen.

Okay I have an input field like such:

<input type="text" id="input1" size="10" name="" value="" class="checked other_amount" onfocus="Toggle('radio1', 'input1');" /> 

I would like to click on a div with an ID of #resetPrompt and fill the empty name attr from the input with "other_amount"

I'm out of ideas its been a long day

Thanks guys,

Matt

like image 506
TikaL13 Avatar asked Feb 25 '10 22:02

TikaL13


People also ask

How do you set an input name?

To add the name of an input element, we use HTML <input> name attribute. The HTML <input> name attribute is used to specify a name for an <input> element. It is used to reference the form-data after submitting the form or to reference the element in JavaScript.

Which function is used to set an attribute in jQuery?

Set Attributes - attr() The jQuery attr() method is also used to set/change attribute values.

What is the use of name attribute in input?

Definition and Usage The name attribute specifies the name of an <input> element. The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted. Note: Only form elements with a name attribute will have their values passed when submitting a form.


2 Answers

$('#resetPrompt').click(function(){     $('#input1').attr('name', 'other_amount'); }); 
like image 139
Alex Weber Avatar answered Nov 01 '22 14:11

Alex Weber


This is for all the googlers out there:

It should be noted that Alex's proposal, though functional in most "real" browsers, does not work in ie 8 and below (jquery 1.6.2). When setting the "name" attribute of an input field, Microsoft, to address a bug, added a fictitious "submitName" attribute when dynamic input fields are attached to the DOM.

To workaround the problem in ie, either force your users to upgrade, use Firefox, Chrome, etc. or you'll need to add the input field manually:

$("#resetPrompt").click(function(){    $("#input1").remove();    $("#input_container").append('<input id="input1" name="' + other_amount + "' type="text" class="checked other_amount" onFocus="Toggle(\'radio1\', \'input1\');" />'); }); 
like image 29
eugene Avatar answered Nov 01 '22 14:11

eugene