$(document).on('click', '.atitle', function(){
//for each data attr - corresponding input value = data.value
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='atitle' data-x='lorem' data-y='ipsum' data-z='dolor'>title</div>
<br>
<input type='text' id='input_x'>
<input type='text' id='input_y'>
<input type='text' id='input_z'>
result:
input_x has value lorem
input_y has value ipsum
input_z has value dolor
$(document).on('click', '.atitle', function() {
// get data of all data attributes
// (it's an object like this { x: "lorem", y: "ipsum", ...)}
let data = $(this).data();
// Set data to input values.
Object.entries(data).forEach(([key, value]) => {
let elem = $(`#input_${key}`);
// Check if elem exists before trying to assign a value.
// Just in case if .atitle contains some data attributes,
// which have no mapping to an input element.
elem && elem.val(value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='atitle' data-x='lorem' data-y='ipsum' data-z='dolor'>title</div>
<br>
<input type='text' id='input_x'>
<input type='text' id='input_y'>
<input type='text' id='input_z'>
you can read this
$(document).on('click', '.atitle', function(){
var title= $(".atitle");
let arr=title.data();
console.log(arr)
$('input').each(function( index ){
$( this ).val(arr[this.id.split("_")[1]])
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='atitle' data-x='lorem' data-y='ipsum' data-z='dolor'>title</div>
<br>
<input type='text' id='input_x'>
<input type='text' id='input_y'>
<input type='text' id='input_z'>
please take a look at this example
const trigger = document.querySelector(".atitle");
trigger.addEventListener("click", clickHandler);
function clickHandler(event) {
const { x, y, z } = Object.assign({}, event.target.dataset);
document.querySelector("#input_x").value = x;
document.querySelector("#input_y").value = y;
document.querySelector("#input_z").value = z;
}
<div class="atitle" data-x="lorem" data-y="ipsum" data-z="dolor">title</div>
<br />
<input type="text" id="input_x" />
<input type="text" id="input_y" />
<input type="text" id="input_z" />
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Please check following code. It's fully independent from keywords of attributes.
$(document).on('click', '.atitle', function(){
var title= $(".atitle");
$.each($(title)[0].attributes, function(key, value) {
var attr_name = value.name
if (attr_name.indexOf('data-') > -1) {
var attr_val = value.value
var attr_idx = attr_name.split('data-')[1]
$('#input_' + attr_idx).val(attr_val)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='atitle' data-x='lorem' data-y='ipsum' data-z='dolor' data-xx='xlorem' data-yy='yipsum' data-zz='zdolor'>title</div>
<br>
<input type='text' id='input_x'>
<input type='text' id='input_y'>
<input type='text' id='input_z'>
<input type='text' id='input_xx'>
<input type='text' id='input_yy'>
<input type='text' id='input_zz'>
Related
I have a textbox that can be append.. and i want to get the values of each textbox
$('#entryData').append('<div><input type="text" id="quantity"></div>');
var total = $('#quantity').val();
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="entryData">
<input type="text" id="quantity">
<input type="button" value="+">
<input type="button" value="Total">
</div>
but I am only getting the first textbox value and not the other textbox
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id='entryData' >
<input type="text" class='quantity'>
<input type="button" value="+" id='add'>
<input type="button" value="Total" id='total'>
</div>
<script>
$(document).ready(function(){
$('#add').click(function(){
$('#entryData').append('<div><input type="text" class="quantity"></div>');
});
$('#total').click(function(){
var total=0;
$('.quantity').each(function(index,quantity){
total=total+parseInt($(this).val());
});
alert(total);
});
});
</script>
I expect this is what you are trying to do?
Or make it like this:
<div id='entryData' >
<input type="number" class='quantity'>
<input type="button" value="+" id='add'>
<input type="button" value="Total" id='total'>
</div>
If you expect numbers - make the field number.
//this should come from helper method file/lib - for reusability
const sum = (accumulator, currentValue) => accumulator + currentValue;
const mapToInt = (idx,element) => { if (element.value !== "") { return parseInt(element.value, 10); } }
$(document).ready(() =>{
$('#add').click( () => {
$('#entryData').append('<div><input type="number" class="quantity" /></div>');
});
$('#total').click( () => {
let total = $(".quantity").map(mapToInt).get().reduce(sum);
console.log ( total );
});
});
Edit: sum (aggregation func) and mapToInt can be reused if you consider having more functional approach.
I have a little problem with my template.
I would like to read in a template with jquery and then find all inputs within this object to manipulate them.
Unfortunately, the inputs are not returned.
I already use the function "checkInputs" in another place.
The target is not a template and it works without problems.
Here's my test code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
And here is my template:
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
The thing is that script tag does not parse the HTML and create a DOM out of it.
Its contents are just a string.
To be able to select from it, you should parse it (you can do it with jQuery) and select from the created (parsed) object.
Notice in the code below I first create a "mini (virtual) DOM" out of your template's text contents:
var miniDOM = $($(target).text());
And now use all selectors having it as context/root. E.g.
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
This finds the elements as you wanted.
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var miniDOM = $($(target).text());
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
miniDOM.find("input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
miniDOM.find("input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
Of course, you could, alternatively, turn that script into any renderable element, like div or span, even if hidden, and you could query it with your original code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="IncomingInformationsTemplate" style="display: none">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</div>
you should find inputs with this method
$('#IncomingInformationsTemplate').find(':input').each(function(i,e) {
console.log((i+1)+'. '+$(e)[0].outerHTML);
$(e).addClass('manipulate-it'); //manipulate it
});
Normally if I add a new input tag I also have to add in Javascript.
I try to collect all value from input tag,
So how to pass value into an object by loop
use tag input name to be object key name also.
Try to use for count
document.getElementById("form1").elements.length
seem it collected the button tag also, how to void it
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" onClick="fc1()" value="Save">
</form>
for(i=0;......)
{
obj.value+'i' = document.forms["form1"]["value"+ (i+1)].value;
}
Same result as this.
function fc1(){
this.value1 = document.forms["form1"]["value1"].value;
this.value2 = document.forms["form1"]["value2"].value;
this.value3 = document.forms["form1"]["value3"].value;
this.value4 = document.forms["form1"]["value4"].value;
const obj = {
"value1": this.value1,
"value2": this.value2,
"value3": this.value3,
"value4": this.value4
};
}
I usually grab inputs by their ID or class:
<input type="text" id="value1">
then grab the value:
const value1 = document.getElementById('value1').value
to cut down on code, maybe throw it in an array:
const valueArray = [value1, value2, value3]
then you can do something like this:
const allValues = {}
valueArray.forEach((value, index) => {
allValues[`value${index + 1}`] = value
})
now when you log allValues you should have what you want. Note, I am using some es6.
What about this ?
var obj = {};
var form = document.getElementById("form1");
form.children.forEach(function(elm){
if(elm.type === 'text'){
obj[elm.name] = elm.value;
}
});
console.log(obj);
try giving same 'class' or 'name' attribute to the text fields.
try var x = document.getElementsByClassName("example");
which gives you the list of all elements with the class name as "example'. Then you can loop around based on the length of x.
References:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try this:
var input = document.forms[0].querySelectorAll('input[type=text]');
var result = Array.from(input).reduce((r, ele) => {
r[ele.name] = ele.value;
return r;
}, {});
console.log(result);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
If you used something like .. I think it will work. :)
var myObj = {};
var elems = document.getElementsByTagName('input'), i;
for (i in elems) {
myObj[value + i] = myObj[i].value;
}
return from getElementsByTagName is an array of all matching tags. there are some wizard answers in here ha. :)
document.querySelectorAll is made for this.
document.querySelectorAll("form[name='form1'] input[type='text']")
will return all input fields of type text in form1 as HTML nodes.
let elements = document.querySelectorAll("form[name='form1'] input[type='text']");
elements.forEach(e => console.log(e.value));
...logs the values of the input fields. Don't make things harder on yourself by hard coding classes or ID's, and this will allow you to target the input elements you need without additional checks or without fetching every input on the page.
Example:
const values = {};
document.querySelectorAll("form[name='form1'] input[type='text']").forEach(element => values[element.name] = element.value);
console.log(values);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
This is an alternative solution done with jQuery.
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
//jQuery solution
const obj = {}
$('#save').click(function(e){
var form = $(this).parent();
var inputs = form.children().not(':input[type=button]');
$.each( inputs, function(){
obj[$(this).attr('name')] = $(this).val();
});
console.log(obj);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>jQuery solution</h2>
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" value="Save">
</form>
JS Solution
//JS Solution
const objs = {}
var button = document.getElementById('savejs');
var form = document.getElementById('formjs');
var element = {};
button.addEventListener('click', function(){
inputs = form.children;
for(i=0; i < inputs.length; i++){
if(inputs[i].name != ""){
objs[inputs[i].name] = inputs[i].value;
}
}
console.log(objs);
})
<h2>JS solution</h2>
<form name="form1" id='formjs'>
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="savejs" value="Save">
</form>
How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
I have HTML like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
</div>
<input type='button' id='add' value='Add'>
jQuery:
$("input#add").live( 'click', function(){
$("#main").append("<br />");
$("#child-0").clone(false).appendTo( $("#main") );
});
Above code is working but it is creating elements with same name. I want to generate it something like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
<div id='child-1'>
<input type='text' name='data[1][name]'>
<input type='text' name='data[1][dob]'>
<input type='text' name='data[1][location]'>
</div>
</div>
What is the simple solution.
Thanks
$("input#add").live( 'click', function(){
$("#main").append("<br />");
var cloned = $("#main div:last").clone(false).appendTo( $("#main") );
cloned.find('[name^=data]').attr('name', function() {
var index = this.name.match(/\[(\d)\]/);
if (index != null && index.length > 1) {
var newIndex = parseInt(index[1], 10) + 1;
return this.name.replace(/\[(\d)\]/, '[' + newIndex + ']');
}
return this.name;
});
});