Jquery one button updates multiple input fields on form - javascript

I am trying to update two input fields in a form when clicking one button. I actually had all the code right when using document.getElementById, but the form that I'm using strips the ID's I set away, so I can't use getbyid. If I know the form field name, how could I change my function to do the same thing? Please note that my form has more than two fields, including a submit button, so I don't want to update those.
This is what I used before (with the ID selector)
Html:
<input type="text" name="field-1" id="info1">
<input type="text" name="field" id="info2">
Populate
JS:
function addTxt(val, id,no)
{
var id = id;
for(var i=1;i<=no;i++){
document.getElementById(id+i).value = val[i-1];
}
}
Fiddle:
http://jsfiddle.net/qwz47phx/3/

Edited with a much simpler and readable approach
function addVal(obj) {
event.preventDefault(); // Prevent page scrolltop on anchor click
$.each(obj, function(k, v) {
$("input[name='"+ k +"']").val( v );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo">
<input type="text" name="bar">
<a href="#" onclick='addVal({foo:"Hello", "bar-baz":"World"})'>Populate</a>
Or with native JS (ES5+):
function addVal(obj) {
Object.keys(obj).forEach(function(name) {
document.querySelector('input[name="' + name + '"]').value = obj[name];
});
}
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="name-with-dashes">
<a href="#" onclick='addVal({foo:"Hello", bar:"World", "name-with-dashes": "Works !"})'>Populate</a>

If you have problems with IDs you can use querySelector to select inputs by name like this:
JS:
function addTxt(val, id, no) {
for (var i = 1; i <= no; i++) {
document.querySelector('input[name="' + id + i + '"]').value = val[i - 1];
}
}
HTML:
<input type="text" name="info1" id="info1">
<input type="text" name="info2" id="info2">
Populate
Demo: http://jsfiddle.net/iRbouh/qwz47phx/6/
I hope this will help you.

You can use a jQuery attribute= selector to grab by name instead of ID.
function addTxt(val, id,no)
{
for(var i=1;i<=no;i++){
var name = id+i;
$("input[name='"+name+"']").val(val[i-1]);
}
}
Please note that this function will be looking for names of info1, info2, info3, etc, just as your original script did. However, in the HTML, you have names of info and info-1. Either the names will have to be changed to fit the function, or the function can be slightly more intricate.
Fiddle: http://jsfiddle.net/qwz47phx/8/

Related

nodeChild.value is null and i dont know why [duplicate]

I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
And this is my JavaScript code:
<script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>
How do I get the value from the text field into JavaScript?
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
Method 1
document.getElementById('textbox_id').value to get the value of
desired box
For example
document.getElementById("searchTxt").value;
 
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0],
for the second one use [1], and so on...
Method 2
Use
document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection
For example
document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.
Method 3
Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection
For example
document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.
Method 4
document.getElementsByName('name')[whole_number].value which also >returns a live NodeList
For example
document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.
Method 5
Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element
For example
document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name
Method 6
document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.
For example
document.querySelectorAll('#searchTxt')[0].value; selected by id
document.querySelectorAll('.searchField')[0].value; selected by class
document.querySelectorAll('input')[0].value; selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name
Support
Browser
Method1
Method2
Method3
Method4
Method5/6
IE6
Y(Buggy)
N
Y
Y(Buggy)
N
IE7
Y(Buggy)
N
Y
Y(Buggy)
N
IE8
Y
N
Y
Y(Buggy)
Y
IE9
Y
Y
Y
Y(Buggy)
Y
IE10
Y
Y
Y
Y
Y
FF3.0
Y
Y
Y
Y
N IE=Internet Explorer
FF3.5/FF3.6
Y
Y
Y
Y
Y FF=Mozilla Firefox
FF4b1
Y
Y
Y
Y
Y GC=Google Chrome
GC4/GC5
Y
Y
Y
Y
Y Y=YES,N=NO
Safari4/Safari5
Y
Y
Y
Y
Y
Opera10.10/
Opera10.53/
Y
Y
Y
Y(Buggy)
Y
Opera10.60
Opera 12
Y
Y
Y
Y
Y
Useful links
To see the support of these methods with all the bugs including more details click here
Difference Between Static collections and Live collections click Here
Difference Between NodeList and HTMLCollection click Here
//creates a listener for when you press a key
window.onkeyup = keyup;
//creates a global Javascript variable
var inputTextValue;
function keyup(e) {
//setting your input text to the global Javascript Variable for every key press
inputTextValue = e.target.value;
//listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
if (e.keyCode == 13) {
window.location = "http://www.myurl.com/search/" + inputTextValue;
}
}
See this functioning in codepen.
I would create a variable to store the input like this:
var input = document.getElementById("input_id").value;
And then I would just use the variable to add the input value to the string.
= "Your string" + input;
You should be able to type:
var input = document.getElementById("searchTxt");
function searchURL() {
window.location = "http://www.myurl.com/search/" + input.value;
}
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
I'm sure there are better ways to do this, but this one seems to work across all browsers, and it requires minimal understanding of JavaScript to make, improve, and edit.
Also you can, call by tags names, like this: form_name.input_name.value;
So you will have the specific value of determined input in a specific form.
Short
You can read value by searchTxt.value
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
<script type="text/javascript">
function searchURL(){
console.log(searchTxt.value);
// window.location = "http://www.myurl.com/search/" + searchTxt.value;
}
</script>
<!-- SHORT ugly test code -->
<button class="search" onclick="searchURL()">Search</button>
<input type="text" onkeyup="trackChange(this.value)" id="myInput">
<script>
function trackChange(value) {
window.open("http://www.google.com/search?output=search&q=" + value)
}
</script>
Tested in Chrome and Firefox:
Get value by element id:
<input type="text" maxlength="512" id="searchTxt" class="searchField"/>
<input type="button" value="Get Value" onclick="alert(searchTxt.value)">
Set value in form element:
<form name="calc" id="calculator">
<input type="text" name="input">
<input type="button" value="Set Value" onclick="calc.input.value='Set Value'">
</form>
https://jsfiddle.net/tuq79821/
Also have a look at a JavaScript calculator implementation.
From #bugwheels94: when using this method, be aware of this issue.
If your input is in a form and you want to get the value after submit you can do like:
<form onsubmit="submitLoginForm(event)">
<input type="text" name="name">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<script type="text/javascript">
function submitLoginForm(event){
event.preventDefault();
console.log(event.target['name'].value);
console.log(event.target['password'].value);
}
</script>
Benefit of this way: Example your page have 2 form for input sender and receiver information.
If you don't use form for get value then
You can set two different id (or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
If you set the same value for two inputs, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver. Later, if you change the order of 2 form in HTML, you need to check this code again
If you use form, then you can use name, address, ...
You can use onkeyup when you have more than one input field. Suppose you have four or input. Then
document.getElementById('something').value is annoying. We need to write four lines to fetch the value of an input field.
So, you can create a function that store value in object on keyup or keydown event.
Example:
<div class="container">
<div>
<label for="">Name</label>
<input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Age</label>
<input type="number" name="age" id="age" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Email</label>
<input type="text" name="email" id="email" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Mobile</label>
<input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
</div>
<div>
<button onclick=submitData()>Submit</button>
</div>
</div>
JavaScript:
<script>
const data = { };
function handleInput(e){
data[e.name] = e.value;
}
function submitData(){
console.log(data.fname); // Get the first name from the object
console.log(data); // return object
}
</script>
function handleValueChange() {
var y = document.getElementById('textbox_id').value;
var x = document.getElementById('result');
x.innerHTML = y;
}
function changeTextarea() {
var a = document.getElementById('text-area').value;
var b = document.getElementById('text-area-result');
b.innerHTML = a;
}
input {
padding: 5px;
}
p {
white-space: pre;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
<input id="new" >
<button onselect="myFunction()">it</button>
<script>
function myFunction() {
document.getElementById("new").value = "a";
}
</script>
One can use the form.elements to get all elements in a form. If an element has id it can be found with .namedItem("id"). Example:
var myForm = document.getElementById("form1");
var text = myForm.elements.namedItem("searchTxt").value;
var url = "http://www.myurl.com/search/" + text;
Source: w3schools
function searchURL() {
window.location = 'http://www.myurl.com/search/' + searchTxt.value
}
So basically searchTxt.value will return the value of the input field with id='searchTxt'.
Short Answer
You can get the value of text input field using JavaScript with this code: input_text_value = console.log(document.getElementById("searchTxt").value)
More info
textObject has a property of value you can set and get this property.
To set you can assign a new value:
document.getElementById("searchTxt").value = "new value"
Simple JavaScript:
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
}

How can to show more than one form value in a alert?

I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll

Serializing a form with dynamic keys

I am looking for a better way to serialize a form with input pairs; one input is for the key, another is for the value. Whoever is using this form could opt to add more key-value input pairs.
I currently have this fiddle to serialize the form, but I am not convinced this is the best/optimal/readable way. Are there any library or method I'm missing that would make this code better?
Code as follows:
HTML:
<div>
<form>
<span>
<input type="text" class="key" id="key1"/><input type="text" class="value" id="value1"/>
</span>
</form>
</div>
Add
Serialize
<div id="serialized-string"></div>
JavaScript :
$(document).ready(function(){
var numberOfPairs = $('.key').length;
$('#add').on('click', function () {
numberOfPairs += 1;
$('div > form').append('<span><input type="text" class="key" id="key'+numberOfPairs+'"/><input type="text" class="value" id="value'+numberOfPairs+'"/></span>');
});
$('#serialize').on('click', function () {
var serialized = "";
for(var x = 1; x <= numberOfPairs; x +=1) {
var keyValuePair = $('#key'+x).val() + "=" + $('#value'+x).val();
if(serialized.length > 0) {
serialized += "&" + keyValuePair;
} else {
serialized += keyValuePair;
}
}
alert(serialized);
});
});
and CSS
span {
display: block;
}
Also, I am not sure if I should properly encode this to URI...
You can use .serialize:
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls, such as <input>, <textarea>, and <select>
Example:
$('#serialize').on('click', function () {
alert($('form').serialize());
});
But this assumes you've provided a name for your form elements.
<input type="text" class="key" name="key1" id="key1"/><input type="text" class="value" id="value1" name="key2" />**strong text**
See http://jsfiddle.net/s2tyS/1/

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Dynamically added fields not working with calendar field

I am trying to attach a calendar field to a dynamically added html code.
Initially, the code shows 3 input fields (as shown in the "p_scents" div).
When the "Add Another Employer" is clicked, it should generate another 3 inputs( as the ones above).
It is working fine for me to generate the first 2 fields (without the calendar field), but when I add the calendar field, it is not working.
<body>
<h2>Add Another Employer</h2>
<div id="p_scents">
<p>
<label>Employer Name</label><input class="dynamic" type="text" name="employern" id="employern" />
<label>Job Title</label><input class="dynamic" type="text" name="jtitle" id="jtitle" />
<label>Start Date </label>
<input type="text" name="startd" class="textfield" />
<script language="JavaScript">
new tcal ({
// form name
'formname': 'form',
// input name
'controlname': 'startd'
});
</script>
</p>
</div>
<script type="text/javascript">
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function() {
if( i <= 10 ) {
$('<p><label>Employer Name</label><input class="dynamic" type="text" name="employern' + i +'" id="employern" /><label>Job Title</label><input class="dynamic" type="text" name="jtitle' + i +'" id="jtitle" /><label>Start Date </label>
<input type="text" name="startd' + i +'" class="textfield" />
<script language="JavaScript">
new tcal ({'formname': 'form','controlname': 'startd' + i +''});</script>Remove</p>').appendTo(scntDiv);
i++;
return false;}
else{
alert('Maximum Reached!');
}
});
$('#remScnt').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
</body>
Sorry, but there is lot of stuff wrong/not good in your code. I'm trying to give some suggestions how to improve this, but first, what's wrong:
IDs have to be unique. In your code, you give multiple elements the same ID. Especially the remove link will not work.
Strings cannot span multiple lines in JavaScript.
Don't add such a bunch of HTML as string. You have a quotation error in this string.
Don't add <script> tags this way (at least here it is not necessary).
My suggestions:
Remove the script tag from the HTML, you don't need it and remove the IDs of the input elements
<h2>Add Another Employer</h2>
<div id="p_scents">
<p>
<label>Employer Name</label><input class="dynamic" type="text" name="employern" />
<label>Job Title</label><input class="dynamic" type="text" name="jtitle" />
<label>Start Date </label>
<input type="text" name="startd" class="textfield" />
</p>
</div>
You also don't need to use live [docs] for the click event handler on #addScnt. Just use click [docs]:
$('#addScnt').click(...
You only need live for elements you add dynamically.
Now the most important thing: How you add new fields.
You can do this very easily, by cloning the existing p element. The only thing you have to remember is to change the name of input fields (add the i) and call the tcal function:
$('#addScnt').click(function() {
if (i <= 10) {
$('#p_scents p:first').clone() // clone
.find('input').attr('name', function(index, value) { // change name
return value + i;
}).end()
.append('Remove') // add remove link
.appendTo(scntDiv);
// init calender
new tcal({
formname: 'form',
controlname: 'startd'+i
});
i++;
return false;
}
else {
alert('Maximum Reached!');
}
});
Reference: clone [docs], attr [docs]
Note that the remove link has a class, not an id. For this link it is better to use delegate [docs]:
$('#p_scents').delegate('.remScnt', 'click', function() {
if (i > 2) {
$(this).closest('p').remove();
i--;
}
return false;
});
Also note that I use closest [docs] here, which only gives the closest p element. If you use parents, you will remove all ancestor p elements and that might result in removing a lot more than you intended.
Last but not least, you also have to make a call to
new tcal ({
// form name
'formname': 'form',
// input name
'controlname': 'startd'
});
because we removed the script tag.
Here is a working demo of all that: http://jsfiddle.net/fkling/ygSn9/ (with empty tcal function).

Categories

Resources