Set form names with javascript loop - javascript

I have a form with which a user can dynamically add text inputs. This generates a form with multiple text inputs that have the same name. If this form is submitted they overwrite each other. To solve this I need change the names so that they are appended with an incremented prefix when the form is submitted. Can anyone help?
Example of form (once three inputs have been added):
<form action="" method="post">
<td class="recipe-table__cell">
<input id="answer" name="the_answer" type="text" value="" >
<input id="answer" name="the_answer" type="text" value="" >
<input id="answer" name="the_answer" type="text" value="" >
</td>
<input type="submit" value="Submit">
</form>
Desired Post output on submission:
Array ( [1-answer] => test [2-answer] => ok [3-answer] => nice)
rather than Array ( [answer] => test )

First, select all of the elements that you want to add the attribute for. This can be done with .querySelectorAll().
Second, loop over those elements.
Third, use .setAttribute() to change the name attribute to append the index from the loop.
Note that you'll also want to increment the ID attribute, as you can't have duplicate IDs on the same page. You'll also want to swap your <td> elements for <div> elements to both allow .querySelectAll() to work correctly, and ensure valid markup.
This can be seen in the following example:
var inputs = document.querySelectorAll("form div input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute("id", "answer" + i);
inputs[i].setAttribute("name", "the_answer" + i);
console.log(inputs[i]); // Added purely to show the change
}
<form action="" method="post">
<div class="recipe-table__cell">
<input id="answer" name="the_answer" type="text" value="">
<input id="answer" name="the_answer" type="text" value="">
<input id="answer" name="the_answer" type="text" value="">
</div>
<input type="submit" value="Submit">
</form>
Hope this helps! :)

Related

Is there a modification of this that can make the form value appear?

So, here's the form
<form action="/missions/basic/3/index.php" method="post">
<input type="hidden" name="file" value="password.php" />
<input type="password" name="password" /><br /><br />
<input type="submit" value="submit" />
<input type=button value="Get Value" onclick="printIt()" /></form>
I have these methods here to try to get the value to appear.
function printIt(){
for (i = 0; i < document.getElementsByName('password').length; i++) {
var x = window.alert(document.getElementsByName('password')[i].value());
window.alert(x);
}
}
I want to know what I can change in those last two methods to get the value to appear.
The function document.getElementsByTagName() returns an array, not one element, so changing your code to window.alert(document.getElementsByName('password')[0].value); should get the first item's value. The first item will most likely be the element in your form you're looking for.

Check if n elements contains data attribute set to true

I have a website where there are five checkboxes, a div that contains another divs which each div contains five input hidden that have a value 1 or empty. That value comes from DB.
That's an example to represent the div container with the divs:
<input checkbox value="a">
<input checkbox value="b">
<input checkbox value="c">
<input checkbox value="d">
<input checkbox value="e">
<div class="container">
<div class="content" data-name="combine">
<input type="hidden" value="" data-name="a" />
<input type="hidden" value="" data-name="b" />
<input type="hidden" value="" data-name="c" />
<input type="hidden" value="" data-name="d" />
<input type="hidden" value="" data-name="e" />
</div>
<div class="content" data-name="combine">
<input type="hidden" value="1" data-name="a" />
<input type="hidden" value="" data-name="b" />
<input type="hidden" value="" data-name="c" />
<input type="hidden" value="1" data-name="d" />
<input type="hidden" value="" data-name="e" />
</div>
</div>
In the javascript code i have this snippet:
if(elementLength > 0) {
$("[data-name='combine'] div.tagsProds").each(function() {
var element = $(this);
$.each(enabledChecks,function(i, v) {
if(element.find("input[name='"+v+"']").val() == "") {
element.append("<div class='blocked'></div>");
element.unbind("click");
element.addClass("js_noSortable");
}
});
});
}
The javascript first checks if the div.container has childs and if it has childs the code iterates each child. On each child i iterate the five each checkbox (enabledChecks) and i see if the input hidden are empty. What i need if that if the five input are empty then append the `div.blocked'.
As i don't have enough reputation to write a comment i write an answer.
First, i think that your answer is quite interesting if you're looking to find a way using a jQuery function, but as i don't know any function to do this i think that you can create an array() and when you check if the input has empty value push it to the array, when the loop finishes you check the length of the array() and if it matches with the number of your checkboxes then append the .blocked
If I understand the question correctly, you want to find divs matching some selector that have no child input elements with non-empty values. The .filter method seems like a good fit here:
$("[data-name='"+name+"'] div.tagsProds")
.filter(function() {
// assert that at least one child input has a value
var $inputsWithValue = $(this).find("input[name='avail_" + v + "'][value!='']");
return $inputsWithValue.length === 0;
})
.each(function() {
// now act on those value-less divs
$(this)
.append("<div class='blocked'></div>")
.addClass("js_noSortable")
.unbind("click");
});
Another selector-only option might look like:
$("[data-name='"+name+"'] div.tagsProds:not(:has(input[name='avail_" + v + "'][value!='']))")
.each(function() {
// now act on those value-less divs
$(this)
.append("<div class='blocked'></div>")
.addClass("js_noSortable")
.unbind("click");
});
JSFiddle: http://jsfiddle.net/nrabinowitz/vrx2wk8g/
Note that the examples above follow the selectors in your sample code, but won't work against your sample markup.

Text field to Hidden field value - value not being set

I'm having an issue with passing hidden values. I have a search field that onclick calls my javascript function with the intention of setting a hidden fields value further down the page.
<div class="search">
<input type="text" name="username" class="mySearch" value="">
<input type="button" class="myButton" value="" onclick="setSearch();">
</div>
My javascript, i is set outside of the function.
setSearch(){
if(i == 0){
$('input:hidden[name="search1"]').val($(".mySearch").val());
}
else if(i == 1)
{
$('input:hidden[name="search2"]').val($(".mySearch").val());
}
i++;
}
and then the field I'm try to set
<div class="sendallHolder">
<form method="post" action="getTweets.php">
<input type="hidden" name="fromTest" id="fromTest"/>
<input type="hidden" name="untilTest" id="untilTest"/>
<input type="hidden" name="latTest" id="latTest"/>
<input type="hidden" name="longTest" id="longTest"/>
<input type="hidden" name="search1" id="search1" />
<input type="hidden" name="search2" id="search2" />
<input type="submit" class="sendAll" value="Gather News!">
</form>
</div>
It runs through the loop twice but each time its not setting the values properly in my hidden fields. the dev tools in chrome tell me that the 'value' is popping up but no value is being set. I'm not entirely sure what I'm doing wrong.
Any ideas?
The :hidden selector doesn't do what you think. It matches elements that have been hidden using CSS, it doesn't match type="hidden" inputs. Just use
$("#search1")
since you have an id on the elements.
Use hidden input ID like this :
$('#search1').val($(".mySearch").val())
$(".mySearch").keyup(addhjc);
function addhjc(){
$('#search2').val($(".mySearch").val());
}
or
$('.myButton').click(function(){
$('#search2').val($(".mySearch").val());
});
also
function setSearch(){
if(i === 0){........
and define i var

Walk through a form in javascript and check for blank inputs?

I apologize for asking such a "noob" question but I'm outside my area of expertise here.
I'm using Dojo 1.9 and I need to walk through a submitted form and determine if any of the input fields are blank. The tricky part is that the form is dynamic, it can contain an array of child elements of each array element, with names like itemList[1].myName:
<form id="businessReferences" action="/yabba/dabba/doo" method="post">
<input id="itemList[0].myName" name="itemList[0].myName" type="text" value=""/>
<input id="itemList[0].myAddress" name="itemList[0].myAddress" type="text" value=""/>
<input id="itemList[1].myName" name="itemList[1].myName" type="text" value=""/>
<input id="itemList[1].myAddress" name="itemList[1].myAddress" type="text" value=""/>
<input id="itemList[2].myName" name="itemList[2].myName" type="text" value=""/>
<input id="itemList[2].myAddress" name="itemList[2].myAddress" type="text" value=""/>
</form>
What is the best way to walk through this form and check to see if all the fields for each parent element are empty? For example if all the fields for itemList[2] are empty? Is there a particular method for doing this? Seems like it would be a fairly common problem but I haven't been able to track down an answer.
Just add an submit button in the form
<form id="businessReferences" action="/yabba/dabba/doo" method="post" onsubmit="return validate()">
<input id="itemList[0].myName" name="itemList[0].myName" type="text" value=""/>
<input id="itemList[0].myAddress" name="itemList[0].myAddress" type="text" value=""/>
<input id="itemList[1].myName" name="itemList[1].myName" type="text" value=""/>
<input id="itemList[1].myAddress" name="itemList[1].myAddress" type="text" value=""/>
<input id="itemList[2].myName" name="itemList[2].myName" type="text" value=""/>
<input id="itemList[2].myAddress" name="itemList[2].myAddress" type="text" value=""/>
<input type='submit' value="Submit"/> <!-- to trigger validation on this button click -->
</form>
Javscript for validation , it will account for dynamically added element also
<script type='text/javascript'>
function validate(){
FromRef = document.getElementById('businessReferences');
for(i=0; i<FromRef.elements.length; i++)
{
if((FromRef.elements[i].value).trim() ==""){ // see if the value is blank popup and alert
alert( FromRef.elements[i].name +"is required");
return false; // not to submit form
}
return true;//submit form
}
</script>

fill hidden filed value using javascript

I have a function called makehash()
I have to fill the value of hash field with the return value of makehash()
<form action="http://example.com/test.php" enctype="multipart/form-data" method="post">
<input type="file" name="datafile" size="40">
<input type="hidden" name="upload_mode" value="0">
<input type="hidden" name="hash" value="">
<input type="submit" value="Upload">
</form>
document.forms[0].elements["hash"].value = makehash();
This assumes you have only one form, if you have more specify the form name instead of 0 or give ID to the hidden input and use document.getElementById instead.
You can do it by grabbing the input (document.getElementsByName) and setting the .value, like this:
document.getElementsByName("hash")[0].value = makehash();
There are other ways as well, if it's unique an id is a good option for example.

Categories