How to get an element by name and set its value - javascript

There should be a simple solution for this. I need to get an input element by name and set its value.
The following Javascript does not work:
x = document.getElementsByName($('#questions').val());
x.value=this.value;
Is there a simple solution using JQuery?

Description
You are mixing normal javascript and jQuery.
Use the attribute selector.
Check out my sample and this jsFiddle Demonstration
Sample
Html
<input type="text" name="nameOfTheInputElement"/>
jQuery
$(function() {
$("input[name='nameOfTheInputElement']").val("your value");
});
​
Edit
If you want, for some reason, change a element which name is a value in another element
then do this. jsFiddle Demonstration
Html
<input type="text" id="questions" value="nameOfTheInputElement"/>
<input type="text" name="nameOfTheInputElement"/>
​jQuery
$(function() {
var name = $("#questions").val();
$("input[name='"+name +"']").val("your value");
});​
More Information
jQuery - Attribute Equals Selector [name="value"]
jsFiddle Demonstration (first sample)
jsFiddle Demonstration (second sample)

A simple, pure JavaScript (and therefore faster) solution:
var x = document.getElementsByName(document.getElementById('questions').value)[0].value = this.value;
I know jQuery's tagline is 'Write less, do more', and in many cases it is true... many cases !== always, though ;-)

getElementsByName() returns a node-list, so you need to get the first one getElementsByName(...)[0]
But you are already using jQuery, so use it. Read some tutorials about the jQuery selectors

Try this
var q = $("#question").val();
var x = $("input[name='" + q + "']").val();
on the 2nd line, variable q, the name provided in input with id 'question', will be enclosed with ' and could contain any supported characters, like space, :, -, etc
If you need the value of a component regardless of its tag, you can do this:
var x = $("[name='" + q + "']").val();
Consider that this approach $("[name='" + q + "']") can return more than one element, but .val() will return only the value of the first element.

If I'm understanding your question correctly, you want to get an element by name, and the name of the element you're selecting will be specified by some dropdown or text area.
Here's my take on it:
Html
<input type="text" id="enteredName">
<button id="doTheStuff">Do the work</button>
<input name="one" value="One">
<input name="two" value="Two">
jQuery
$('#doTheStuff').click(function(){
var objectOfInterest = $('[name=\'' + $('#enteredName').val() + '\']');
alert(objectOfInterest.val());
});
Working example
Here's another working example using a dropdown to specify the selection name.

$('#form-id input[name="name-input"]').val('your value');

Related

Jquery get element by id, multidimensional array

I'm trying to get the value of a specific html input that is named like:
<input type="hidden" value="." id="grid[0][0]">
where [0][0] could be any value within a foreach loop.
using Jquery:
var currVal = $('#grid['+x+']['+y+']').html();
I'm getting an undefined value. Not sure whether it's a syntax problem. I haven't found a similar example so I'd appreciate any help on this. Thanks!
It actually is a syntax problem. jQuery interprets "#grid[...]" as an HTML element with the ID "grid" and some attribute (or other meta stuff) just like CSS would.
To solve simply escape the [ and ], like this:
$('#grid\\[' + x + '\\]\\[' + y + '\\]').val()
That should do it :)
Edit: As noted by Josh Crozier, the html() method is supposed to be used in normal tags (like div). For input, select or textarea you should use val() -- Docs on that: http://api.jquery.com/val/
You can also do :
var currVal = $('input[id="grid['+x+']['+y+']"]').val();

Remove a character from the middle of a string: without removing inner element

This one has me stumped. I want to remove the "+" from a label element. Here's the HTML:
<label class="option" for="edit-attributes-21-33">
<input type="radio" id="edit-attributes-21-33" name="attributes[21]"
value="33" checked="checked" class="form-radio"> 4 oz, +$15.00</label>
I started with this
$(".option").each(function(index, value) {
$(this).text( $(this).text().replace("+", ""));
})
This removes the "+" but also strips out the input element. So then I tried:
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).text(newString);
})
This makes a string of the correct html mark-up, but it's a string and is passed back to the DOM that way. I've seen another post with the same problem, but no solution.
You can achieve what you want using your code by using .html() instead of .text():
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).html(newString);
});
Here's the JQuery .html() method ref: https://api.jquery.com/html/
Here's the Fiddle: https://jsfiddle.net/Darkseal/1c572Luw/
I also slightly modified your <input> end tag to make it XHTML compliant.
What you're looking for is called a textNode. I gave your label an ID to make it easier, but the priciple remains the same for other selectors:
var node = document.getElementById("example").childNodes[2];
node.nodeValue = node.nodeValue.replace("+", "");
With a simple demo.
You should try to use plain JS as much as you can in favour in jQuery. Plain JS is often a lot faster than jQuery is.
After the comment, if you don't know the exact position of the textnode, check this.
Late answer, just for the sake of showing a different approach using jQuery.
Here you would keep the input state, and wouldn't have the risk of replacing chars that you don't want to. Let's say you used + somewhere else, not just on the label text.
$(function () {
$('label.option').each(function () {
var label = $(this);
var input = $('input.form-radio', this);
var text = label.text();
// Clean up the label contents.
label.empty();
// Replace the char occurrences.
text = text.replace(/\+/g, "");
// Append both the input and the modified text.
label.append(input).append(text);
});
});
Demo

Using variables in javascript to reference html elements dynamically

I am trying to use jQuery / javascript to remove a class from a named input element if a checkbox is ticked.
I have several checkboxes, each with a accompanying hidden (on page load) text input field.
The checkbox and text input field are named "question_X" and "question_X_description" respectively. (where X is a number 0 to 100, say)
As such I'm trying to define a variable in my code that is defined as "this element's name"+"_description", and then use that to define the suitable element to remove the class from.
Here is what I've tried:
$('input:checkbox').change(function(){
var x = $(this).attr('name').'_description';
if($(this).is(":checked")) {
$('input[name="x"]').removeClass("hidden");
} else {
$('input[name="x"]').addClass("hidden");
}
});
However, nothing happens when the any checkbox is checked. Am I referencing my variable correctly?
Use your console, It will have error messages.
First issue
var x = $(this).attr('name').'_description';
^^^
That is not how you build a string in JavaScript. JavaScript does not use . to join strings. It uses +
var x = $(this).attr('name') + '_description';
Second issue
$('input[name="x"]').
You are not looking for the string you built, you are looking for an element with the name x
Needs to be
$('input[name="' + x + '"]').
$('input[name="x"]').removeClass("hidden");
Will be looking for:
<input name="x" />
Try
$(name="'+x+'").removeClass("hidden");
Use document.getElementById('element_name')
Example of HTML element:
<input type="text" id="element_name">

Count Dynamically created html elements with jquery

I am counting the number of inputs on the current document that have value. It works fine, except for when I have dynamically added more inputs. I can't get there values.
For example I may have
<input id="participant-1"/>
<input id="participant-2"/>
...
Dynamically created after button click
<input id="participant-15" />
I'll get the value of each one in a for loop like
for(var i =1 ; i <25; i++)
{
...$('input#participant-' + i).val();
}
Now when I run a for loop to check the value of each one of these inputs it only gets the values of the inputs that weren't dynamically created. I have looked at the other questions on here and I still can't see how to apply something like .on() to what I am trying to accomplish.
NEW FOLLOW UP QUESTION
ok, now I think this is where I need more clarification concerning how to use the .on.
I have a jsfiddle here: JsFiddle example
where I create new elements and on blur of all text boxes I would like to calculate how many of the elements have value and log it. Now it currently will respond from blur event with elements who were static. It doesn't work for dynamically created elements
Give it a common class:
<input class="textbox" id="participant-1"/>
<input class="textbox" id="participant-2"/>
And get it like:
var values = [];
$('.textbox').each(function(){
values.push($(this).val());
});
console.log(values)
And to answer the edit:
The Syntax should be : $(container_selector).on(event_type, target_selector, callback)
JSFiddle Demo
$('.name').on('blur', 'input', calculate_total);
Could also consider the use of the CSS attribute selector.
http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
$("input[id|=participant]").each(function(){
// something
});
Using a class selector will save time here.
<input id="participant-1" class="participant"/>
<input id="participant-2" class="participant"/>
Then use a simple count call...
var count = $('.participant').length
alert ('You have ' + count + ' Counted Inputs');
//result is 2
Hope you find this useful

jquery escape square brackets to select element

Consider a input element
<input id="meta[152][value]" type="text" />
Here the input field is dynamically generated. I need to select that field. So I used,
alert($('#meta[152][value]').val());
But this seems to be invalid. After searching I found, that the "square brackets" need to be escaped like #meta\\[152\\]\\[value\\]
So how to do that ?
I currently use this code,
var id = "#meta[152][value]" // (I get this value by another method) I need the escaping to be done here. So that i can use as
/** I need the value of id to be escaped using regex,replace or any other method
to get #meta\[152\]\[value\]
and not manually **/
alert($(id).val());
Your suggestions will be helpful !
The following should work:
alert($('#meta\[152\]\[value\]').val());
or
var id = "#meta\[152\]\[value\]";
alert($(id).val());
Working Example
Conversion Function:
function ConvertValue(id)
{
var test = id.replace(/[[]/g,'\\\\[');
return "#" + test.replace(/]/g,'\\\\]');
}
Conversion Example
If you feel more comfortable without escaping you also use the attributes selector and search for the element with that id like this: $("[id='meta[152][value]']")
The simplest way is just to use the regular getElementById, which requires no escaping:
document.getElementById("meta[152][value]").value;
this shoudl work for you, you almost had it:
$(document).ready(function() {
var id = "#meta\\[152\\]\\[value\\]";
alert($(id).val());
});
Um, just put the escaped value right in your string.
var id = "#meta\\[152\\]\\[value\\]";
See it working here
You can use the _.escapeRegExp method from the Lodash library.
console.log($('#' + _.escapeRegExp('meta[152][value]')).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<input id="meta[152][value]" type="text" value='Test' />

Categories

Resources