Javascript change fields value by name - javascript

I have a form where some fields have the same element name. Is there a way to change the value of all the fields with the same name?

1) Use getElementsByName to put the elements in an array.
2) Loop over the array and set each element's value.
code:
var els=document.getElementsByName("yourElementNameHere");
for (var i=0;i<els.length;i++) {
els[i].value = "yourDesiredValueHere";}
If you only want to change the elements with that name in the form, use the form instead of document, example: document.getElementById("yourFormID").getElementsByName(...)

sample form
<form name="form1">
<input type="button" name="buttons" value="button1">
<input type="button" name="buttons" value="button2">
<input type="button" name="buttons" value="button3">
</form>
script
var form = document.form1; // form by name
var form = document.forms[0]; // same as above, first form in the document
var elements = form.buttons; // elements with same name attribute become a HTMLCollection
for (var i=0; i<elements.length; i++)
elements[i].value = elements[i].value.replace("button", "buttoff");
http://jsfiddle.net/yGV3R/

you can do more simple with JQUERY
example :
html
<div id="form">
<input type="text" name="myinput" vale="yussan" />
</div>
js
var value = $('#form input[name=myinput]').val()

Related

Javascript getElementById based on ID formed using fixed name and input number

I am trying to create ID dynamically in the HTML object and use of getElementById() in my javascript to access the HTML input value based on the button I clicked and insert into their respective HTML Select list.
My HTML snippets:
<input type="text" id="addDesc1"><input type="button" value="Add" onclick="addDescText(1)">
<input type="text" id="addDesc2"><input type="button" value="Add" onclick="addDescText(2)">
....
....
<select id="desc1">....</select>
<select id="desc2">....</select>
My javascript snippets:
function addDescText(id) {
var descText = document.getElementById("addDesc".concat(id)).value;
var selList = document.getElementById("desc".concat(id));
....
....
some javascript to add the respective description to their respective select list
....
}
concat() is an array method, you can not use that on string. Simply use + to concatenate the parameter with the string.
Demo:
function addDescText(id) {
var descText = document.getElementById("addDesc"+id).value;
var selList = document.getElementById("desc"+id);
console.log(descText);
console.log(selList);
}
<input type="text" id="addDesc1"><input type="button" value="Add" onclick="addDescText(1)">
<input type="text" id="addDesc2"><input type="button" value="Add" onclick="addDescText(2)">
<select id="desc1">....</select>
<select id="desc2">....</select>
I would encourage you to make use of the event parameter that is passed to all event handlers (on-click-event in your case) and add that handler programmatically.
A possible solution would be
HTML
<input type="text" id="text1">
<input type="button" value="Add" class="add-desc-button" data-target="1">
JS
// get all buttons
let allButtons = document.querySelectorAll('.add-desc-button')
// add event handler
for (let i=0; i<allButtons.length; i++) {
allButtons[i].addEventHandler('click', addDescriptionHandler)
}
// event handler
function addDescriptionHandler(event) {
// retrieve the number you passed in before like this
let number = event.target.getAttribute('data-target')
// ... your code here
}

jquery - copy value of input from one form to another (form and input named the same)

I would like to copy the value from an input in one form to the value of an input(with the same name) of the next form down. The forms and inputs are named the same. All it needs to do is copy the value of the title input to the title input one form down.
<form>
<input name="file" value="1.xml">
<input name="title" id="title" value="Smith">
<input type="submit" id="copy-down" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title" value="Anderson">
<input type="submit" id="copy-down" value="copy">
</form>
etc...
In this case when the top "copy" button is clicked I would like jquery to overwrite Anderson with Smith.
$('#title').attr('value'));
Gives me Smith but I'm not sure what to do with that value once I have it.
Change HTML to this:
<form>
<input name="file" value="1.xml">
<input name="title" id="title1" value="Smith">
<input type="submit" id="copy-down1" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title2" value="Anderson">
<input type="submit" id="copy-down2" value="copy">
</form>
Javascript:
function copyHandler() {
var copyVal = document.getElementById("title1").value;
var replaceInput = document.getElementById("title2");
replaceInput.value = copyVal;
}
document.getElementById("copy-down1").onclick = function(){
copyHandler();
return false;
}
Some notes:
This is so straightforward in vanilla javascript that I didn't add the jQuery code.
You should never assign multiple elements to the same ID, class or name can be used for that purpose.
The return false; portion of the onclick function is necessary so that the form doesn't reload when you click your submit button.
Let me know if you have any questions.
you can try
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var GetNameAttr = $(this).find('input:nth-child(2)').attr('name');
var GetTitleValue = $(this).find('input:nth-child(2)').val();
var NextFormNameAttr = $(this).next('form').find('input:nth-child(2)').attr('name');
if(NextFormNameAttr == GetNameAttr){
$(this).next('form').find('input:nth-child(2)').val(GetTitleValue );
}
});
});
Note: this code will change the second input value in next form with
the second input value of form you click if the name is same .. you
can do the same thing with the first input by using :nth-child(1)
Demo here
if your forms dynamically generated use
$('body').on('submit','form', function(e){
instead of
$('form').on('submit', function(e){
for simple use I create a function for that
function changeNextValue(el , i){
var GetNameAttr1 = el.find('input:nth-child('+ i +')').attr('name');
var GetTitleValue1 = el.find('input:nth-child('+ i +')').val();
var NextFormNameAttr1 = el.next('form').find('input:nth-child('+ i +')').attr('name');
if(NextFormNameAttr1 == GetNameAttr1){
el.next('form').find('input:nth-child('+ i +')').val(GetTitleValue1);
}
}
use it like this
changeNextValue($(this) , nth-child of input 1 or 2);
// for first input
changeNextValue($(this) , 1);
// for second input
changeNextValue($(this) , 2);
Working Demo

select particular input field name of particular form

i have some html code like this
<form name="first"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
<form name="second"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
i want to select "secondText" of form "second" using jquery or javascript and i want to change value of it using jquery.
Using jQuery:
var element = $("form[name='second'] input[name='secondText']");
Using vanilla JS:
var element = document.querySelector("form[name='second'] input[name='secondText']");
Changing the value: element.val(value) or element.value = value, depending of what you are using.
To the point with pure JS:
document.querySelector('form[name=particular-form] input[name=particular-input]')
Update:
This selector will return the input named "particular-input" inside form named "particular-form" if exists, otherwise returns null.
The selector filter "form[name=particular-form]" will look for all forms with name equals "particular-form":
<form name="particular-form">
The selector filter "input[name=particular-input]" will look for all input elements with name equals "particular-input":
<input name="particular-input">
Combining both filters with a white space, I mean:
"form[name=particular-name] input[name=particular-input]"
We are asking for querySelector(): Hey, find all inputs with name equals "particular-input" nested in all forms with name equals "particular-form".
Consider:
<form name="particular-form">
<input name="generic-input">
<input name="particular-input">
</form>
<form name="another-form">
<input name="particular-input">
</form>
<script>
document.querySelector('form[name=particular-form] input[name=particular-input]').style.background = "#f00"
</script>
This code will change the background color only of the second input, no matter the third input have same name. It is because we are selecting only inputs named "particular-input" nested in form named "particular form"
I hope it's more clear now.
;)
By the way, unfortunately I didn't found good/simple documentation about querySelector filters, if you know any reference, please post here.
// Define the target element
elem = jQuery( 'form[name="second"] input[name="secondText"]' );
// Set the new value
elem.val( 'test' );
Try
$("form[name='second'] input[name='secondText']").val("ENTER-YOUR-VALUE");
You can do it like this:
jQuery
$("form[name='second'] input[name='secondText']").val("yourNewValue");
Demo: http://jsfiddle.net/YLgcC/
Or:
Native Javascript
Old browsers:
var myInput = [];
myInput = document.getElementsByTagName("input");
for (var i = 0; i < myInput.length; i++) {
if (myInput[i].parentNode.name === "second" &&
myInput[i].name === "secondText") {
myInput[i].value = "yourNewValue";
}
}
Demo: http://jsfiddle.net/YLgcC/1/
New browsers:
document.querySelector("form[name='second'] input[name='secondText']").value = "yourNewValue";
Demo: http://jsfiddle.net/YLgcC/2/
You can try this line too:
$('input[name="elements[174ec04d-a9e1-406a-8b17-36fadf79afdf][0][value]"').mask("999.999.999-99",{placeholder:" "});
Add button in both forms. On Button click find nearest form using closest() function of jquery. then using find()(jquery function) get all input values. closest() goes in upward direction in dom tree for search and find() goes in downward direction in dom tree for search. Read here
Another way is to use sibling() (jquery function). On button click get sibling input field values.

unable to post data in dynamic form

I have created a form with dynamic field. but i m getting confused that how should i post data into database. because there would be different field according to different users.
here is the basic code with one dynamic field
function add2(type) {
var element = document.createElement("textArea");
var label=prompt("Enter the name for lable","label");
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+label;
element.setAttribute("type", type);
element.setAttribute("name", type);
var col=prompt('Enter the no of columns');
element.setAttribute("cols",col);
var row=prompt('Enter the no of rows');
element.setAttribute("rows",row);
var rohit = document.getElementById("raj");
rohit.appendChild(element);
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+"<br/>";
}
here is the calling of this function.
<input type="button" value="Text Area" onclick="add2('textarea')"><br/>
</div>
<div id="content" style="height:200px;width:400px;float:left;">
<form action="#" method="post">
<span id="raj">&nbsp</span>
<input type="submit" value="submit"></div>
help me guys what should i do to store the dynamic elements into database
and what fields should i put into database
Store the field values separated in one hiddenfield, and get them from the serves side.
<input id="values" type="hidden" value="value1,value2,value3">
on submit:
var Valuearray = values.value.Split(',');

Trying to find selected radio button. What's wrong?

I can read out text field values, but when I try to find the selected radio button, I get nothing.
$(document).ready(function(){
$("form#create_form").submit(function() {
var title = $('#title').attr('value');
var owner = $('#owner').attr('value');
var users = $('#users').attr('value');
var groups = $('#groups').attr('value');
var begin_date = $('#begin_date').attr('value');
var end_date = $('#end_date').attr('value');
// get selected radio button
var type = '';
for (i=0; i<document.forms[0].type.length; i++) {
if (document.forms[0].type[i].checked) {
type = document.forms[0].type[i].value;
}
}
HTML:
<div class="create-new">
<form id="create_form" name="create_form" action="" method="post">
...
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course" type="radio" /> Course <br/>
<button class="n" type="submit">Create</button>
</form>
What am I doing wrong?
I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):
$('input:radio[name=type]:checked').val();
This solution is an example on .val().
The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).
Update
I tested your original function with the following fiddle and it works:
http://jsfiddle.net/nujh2/
The only change I made was adding a var in front of the loop variable i.

Categories