How to get/set values to input fields using jQuery? [duplicate] - javascript

This question already has answers here:
How can I get the data-id attribute?
(16 answers)
Closed 3 years ago.
I know to get/set values to input fields using jQuery like follow example.
//Get
var bla = $('#txt_name').val();
//Set
$('#txt_name').val(bla);
I want to get/set values using data attribute. For an example, if I have following input I want to set/get values using "data-wpt-id".
<input type="text" data-wpt-id="wpcf-latitude">
Note : Please note that this input field doesn't have id attribute.

You need to use Attribute Selector
//Get
var bla = $('input[data-wpt-id="wpcf-latitude"]').val();
//Set
$('input[data-wpt-id="wpcf-latitude"]').val(bla);

// Get
var bla = $('input[data-wpt-id="wpcf-latitude"]').val()
// Set
$('input[data-wpt-id="wpcf-latitude"]').val(bla)

You can do it like this:
$('input[data-wpt-id]').val(function() {
return $(this).data("wpt-id")
});
Demo
$('input[data-wpt-id]').val(function() {
return $(this).data("wpt-id")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" data-wpt-id="wpcf-latitude">

Following the jQuery documentation for the data function: https://api.jquery.com/data/
Following the Vanilla documentation for the dataset attribute: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset
Example:
<input type="text" class="container" data-wpt-id="5">
// jQuery
const $inputElement = $('.container');
const wptId = $inputElement.data('wptId');
console.log(wptId); // 5
$inputElement.data('wptId', 10);
console.log($inputElement.data('wptId')); // 10
// Vanilla
const inputElement = document.querySelector('.container');
const wptId= inputElement.dataset.wptId|| 0;
console.log(wptId); // 5
inputElement.dataset.wptId= 10;
console.log(inputElement.dataset.wptId); // 10
// If the `<input>` element has no Id/Class, you can use following selector instead:
const $jquery = $('input[data-wpt-id]');
const vanilla = document.querySelector('input[data-wpt-id]');

Related

Which API I need to use instead of serializeArray to get the custom attributes of fields?

I'm using serializeArray() to retrive the form attributes. When I try to get the attributes, I'm receiving name and value for all the fields.
I have checked the documentation https://api.jquery.com/serializeArray/. I understood it will return the name and value of all the fields.
Now I have few custom attributes for some fields. I want to retrieve them using those custom attributes.
How can i achieve this?
Here is my logic.
var data = $('form').serializeArray();
var newData = {};
var queue = {};
data.forEach(function(field) {
if( field.customField != undefined && field.customField.indexOf("true")>=0 ) {
queue[field.name] = frm.value
} else {
newData[frm.name] = frm.value;
}
});
I need to get that customField attribute, I'm adding that to the HTML field attribute.
May not be the best, but you can do like this.
Let's say you have set of text boxes, text areas and so on with custom data attributes in it. What I am doing here is adding a class to those fields that you need to get value / data attributes in it.
Let's take the following HTML as an example.
HTML
<form id="frm">
<input class="serialize" type="text" name="title1" value="Test title 1" data-test1="test AAA" data-test2="test BBB" /><br/>
<input class="serialize" type="text" name="title2" value="Test title 2" data-test1="test CCC" data-test2="test DDD" /><br/>
<textarea class="serialize" data-test1="textarea test 1">TEST 22 TEST 11</textarea>
<button id="btn" type="button">Serialize</button>
</form>
What I am doing here is iterating through fields which has class .serialize and putting value, name, data attributes and so on to an array.
jQuery
$(document).ready(function(){
$('#btn').on('click', function(e) {
var dtarr = new Array();
$(".serialize").each(function(){
var sub = new Array();
sub['name'] = $(this).attr('name');
sub['value'] = $(this).val();
//data attribute example
sub['data-test1'] = $(this).data('test1');
sub['data-test2'] = $(this).data('test2');
dtarr.push(sub);
});
// This will give you the data array of input fields
console.log(dtarr);
});
});
Hope this helps.

How do I use JavaScript to display one value in multiple places marked by elements with the same class? [duplicate]

This question already has answers here:
What is wrong with this getElementsByClassName call in Javascript? [duplicate]
(4 answers)
Closed 9 years ago.
I am trying to show the same text value in designated elements marked by the same class. Basically, this text is a value that I am getting from a form input tag. I am trying to do this with JavaScript using a getElementById to gather the text value and then getElementsByClassName to replace the text value in specified places of a page. Please see the following code first in HTML:
collective noun: <input type="text" id="noun1" onkeypress="runGather()"><br>
something the <i class="collective_noun">collective noun</i> can make: <input type="text" id="noun2"><br>
adj describing <i class="collective_noun">collective noun</i>: <input type="text" id="adj"><br>
and then in the JS file:
function runGather() {
var noun1 = document.getElementById("noun1").value;
var collective_noun = document.getElementsByClassName("collective_noun").value;
for (var i = 0; i < noun1.length; i++) {
collective_noun[i].innerHTML = noun1;
}
}
You're setting collective_noun to just a value when you want to use the nodelist that's returned, and you're trying to loop through noun1, which is just the value of the node. Try this instead:
var i, l,
noun_1,
collective_nouns;
noun_1 = document.getElementById('noun_1').value;
collective_nouns = document.getElementsByClassName('collective_noun');
for (i = 0, l = collective_nouns.length; i < l; i += 1) {
collective_nouns[i].innerHtml = noun1;
}
Instead of using plain JavaScript, you could save yourself the headache and use jQuery. Here's a one-line example using jQuery:
$(".collective_noun").text( $("#noun1").val() );

Jquery Select all elements with data attribute common name [duplicate]

This question already has an answer here:
how do I find elements that contain a data-* attribute matching a prefix using jquery
(1 answer)
Closed 9 years ago.
I'm trying to use jQuery to select all the inputs in my form that have a data attribute with a similar name.
This is my form:
<form id = "myForm">
<input name="name" data-valid-presence=true >
<input name="age" data-valid-biggerThan="18" >
<input name="email[0]" data-valid-email=true >
<input name="email[1]" data-valid-email=true >
</form>
and my jQuery selector is:
var inputs = jQuery("#myForm").find("input[data-valid-email],[data-valid-length],[data-valid-presence], [data-valid-biggerThan]");
I'm looking for a way to select all the inputs that have a data-valid-* in them without having to find them one by one like this.
Any ideas?
You can use jQuery.filter:
var inputs = $('form').find('input').filter(function() {
var matched = false;
$.each(this.attributes, function(attr) {
if ( matched ) return;
matched = /^data-valid/.test(this.name);
});
return matched;
});

Get values of all textboxes with same name attributes in jquery

I need to get values of all textboxes with same name attributes using jquery.
<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]">
<input type="text" id="text3" name="text[]">
How can I get all values of textbox text[] and compare it using jquery.
I tried using
var values = $("input[name='text[]']")
.map(function(){return $(this).val();}).get();
but am no successful.
You can use map method and store the values into an array.
$(function(){
var values = $('input[name="text[]"]').map(function(){
return this.value
}).get()
})
http://jsfiddle.net/UugWW/
This one should work :
$('input[name="text[]"]');
You can loop on it to get all values.
$('input[name="text[]"]').each(function() {
alert($(this).val());
});
Let's split the requirement into smaller problems.
First you want to select all those inputs.
var $inputs = $("input[name='text[]']")
It returns a jQuery object, containing all the input named text[].
You also might not need to use square brackets into the name.
var inputs = $inputs.get();
Extract the matching elements into a plain Array, so that we can now access Array's prototype methods, such as Array.prototype.map.
var values = inputs.map(function takeValue(input) {
return input.value;
});
Use a selector like this:
$('input[type="text"][name="text[]"')
var textboxcount = document.getElementsByName("text").length;
var textvalue="";
for (var i = 0; i < textboxcount ; i++) {
textvalue= textvalue + document.getElementsByName("text").item(i).value;
}
alert(textvalue);

How to parse a variable in Javascript

I'm trying to use this code:
var field="myField";
vals[x]=document.myForm.field.value;
In the html code I have
<form name="myForm">
<input type='radio' name='myField' value='123' /> 123
<input type='radio' name='myField' value='xyz' /> xyz
</form>
But this gives me the error:
document.myForm.field is undefined
How can I get field to be treated as a variable rather than a field?
Assuming that your other syntax is correct (I havne't checked), this will do what you want:
var field="myField";
vals[x]=document.myForm[field].value;
In JS, the bracket operator is a get-property-by-name accessor. You can read more about it here.
Use the elements[] collection
document.forms['myForm'].elements[field]
elements collection in DOM spec
BTW. If you have two fields with the same name, to get the value of any field, you have to read from:
var value = document.forms['myForm'].elements[field][index_of_field].value
eg.
var value = document.forms['myForm'].elements[field][0].value
and, if you want to get value of selected radio-button you have to check which one is selected
var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
You have to do it like this:
var field = "myField";
vals[x] = document.myForm[field].value;
or even
vals[x] = document.forms.myForm.elements[field].value;
Based on your tags, it seems that you are using jQuery. If so, you can just do this and it will make your life much easier:
var vals = new Array();
$("form[name='myForm'] :radio").each(function() {
vals.push($(this).val());
});
:-D

Categories