I need a way to change the value of an input box by referring to it by form and class name. Given a form that looks like this:
<form name="foo">
<input type="text" class="bar" value="someval" />
</form>
Is there a one-line solution to this? I've tried some things such as:
document.foo.getElementsByClassName('bar')[0].setAttribute("value", "newvalue");
And
document.forms['foo'].getElementsByClassName('bar')[0].setAttribute("value", "newvalue");
To no avail. There must be something obvious I'm missing, but what?
This is precisely what .querySelector() was designed to help with. You can pass any valid CSS selector to it and it will return the first element that matches the query or undefined if no match is found.
And, don't use .getElementsByClassName() or document.forms (ever) as they are both ancient techniques that either introduce major performance issues or non-modern approaches that are inferior to the APIs we have today.
// Find the input element with a class of "bar" that is a direct child of a form with a name attribute of "foo"
document.querySelector("form[name='foo'] > input.bar").value = "blah"
<form name="foo">
<input type="text" class="bar" value="someval" />
</form>
Try this:
<form>
<input type="text" class="bar" value="someval" />
</form>
<script>
document.getElementsByClassName("bar")[0].value = "newvalue";
</script>
You can use something like this
document.forms[0].querySelector(".bar").value
And if you have multiple forms, just loop through document.forms and get values by class name, use querySelector or select by id whatever suits you.
Hope this helps.
Related
I have a total of two input values. Only one value passes to the url of the next page, but both should. What's causing this?
JSFiddle: http://jsfiddle.net/p8dCC/
HTML:
<!--form action="device" onSubmit=" get_search(); return false;" id="search-form-4" method="get" target="_top"-->
<div class="fix">Brand</div>
<input class="inputs" type="text" id="search_id" name="q3" placeholder="Send this" required="required" />
<br/><br/>
<div class="fix">Model</div>
<input class="inputs" type="text" id="search_id" name="q4" placeholder="And send this one too" required="required" />
<br/><br/>
<input id="search-button" class="" type="submit" value="continue" data-target="http://www.google.com/?item-description" />
<!--/form-->
You have two elements with the same id in html. So when you do this $('#search_id').val() only one of them will get evaluated and not both. Ids are supposed to be unique
After testing your code in a test page, I found that both inputs were in fact being passed through the URL.
You have commented out the form tags which I'm not sure if you did just for purposes on here.
kjs is correct as well, though using the same id would only effect the HTML. Using get as the method would bypass this issue as it would be passed the unique "name" attribute.
A form tag is required if you expect the html submission mechanism to work correctly on its own.
In the Javascript you posted though, you are treating document.location as an html element, wrapping it with jquery, then trying to use jquery's attr method on it. This won't work. Just access "location.href" directly without using jquery.
Additionally, as pointed out by another answer, your ids should all be unique.
I have a hidden field in my page like so:
<hidden id="tsDaySchedule01" value="7.50"></hidden>
When I try to access it with the following code, the alert returns blank:
alert($("#tsDaySchedule01").val());
Now when I use attr("value") like below, it works without issue:
alert($("#tsDaySchedule01").attr("value"));
Lastly, I would like to point out we have other non-hidden text fields within the page that work without issue using val().
I would like to have a better understanding as for what is going on here. Does anybody have an explanation?
<hidden/> isn't a valid HTML element. If you're wanting a hidden input you'd use:
<input type="hidden" />
jQuery's .val() method only works on input, select and textarea elements. To get this to work for you, change your <hidden/> element to:
<input type="hidden" id="tsDaySchedule01" value="7.50" />
.val() method only works with text-box type of element input and textarea elements.
you should use
<input type='hidden' id="tsDaySchedule01" value="7.50">
Maybe you need to use :
<input type='hidden' id="tsDaySchedule01" value="7.50">
i often use this notation when i name my controls in order to get an array in POST or GET.
<input name="color[1]" type="text" />
<input name="color[2]" type="text" />
<input name="color[3]" type="text" />
so in my scripts i can do
<?php $data=$_GET["color"];
for each ($color as $key=>$value) {
doSomething();
} ?>
Often happens that i need to get those id back in javascript , but i cannot get them , so i often add an ID to each element in html like that
<input name="color[3]" id="color_3" type="text" />
so that i can use document.getElementsById('color_3')
Instead i would like to find way to use document.getElementsByName(color[3])...
but i cannot really get it to work.
Any help?
If you want all of the color inputs, you can use querySelectorAll instead to query for the name attribute:
document.querySelectorAll("input[name^='color[']")
This looks through the document for all input tags whose name attribute starts with color[. Here is a fiddle for this.
If you only want color[3], you can use:
var color3 = document.getElementsByName("color[3]");
console.log(color3[0]);
<input name="color[3]" id="color_3" type="text" />
var element = document.getElementsByName("color[3]");
alert(element[0].id);
It works fine .. The thing you should have in your mind is Return type is an array of elements not a single element
I have a form for which I cannot change the input value field names.
One such field is in the HTML as follows:
<body>
<form id="f" method="get" action="/code/submit.php">
<input type="text" name="var[list]" id="ixv[list]" value="">
<button type="button" title="Save" onclick="check();">
</form>
</body>
Now in my javascript, I want to access that input value.
I tried this, and of course it doesn't work since [] looks
like an array in JS.
function check() {
var x=var[list].value;
alert(x);
}
The problem is that the variable name has [] in it. How can I get
that input field value in javascript?
this works:
http://jsfiddle.net/mqv82/1/
<input type="text" name="var[list]" id="ixv[list]" value="foo">
alert(document.getElementById('ixv[list]').value);
Try it like this:
var x = document.getElementsByName("var[list]")[0].value;
In modern browser, use querySelectorAll
document.querySelectorAll('[name="var[list]"]')[0].value
or if you know id try getElementById
document.getElementById('ixv[list]').value
or getElementsByName
document.getElementsByName('var[list]')[0] .value
Above three will returns same result
I currently have some third party client-side "magic widgets" library that I have to deal with... :) All I have to do really is to add some small amount of behavior to those things with jQuery to accommodate for some simple business rules. A lot of times, I find myself selecting a bunch of elements in the same way. Since "magic widgets" are already super heavy on JS, and I even notice it on my fast machine, I was trying to keep my own JS to an absolute minimum. So, given that the user clicks on one of the following inputs, what is the most efficient way to select all the inputs, including the clicked one, in the following structure with jQuery?
<div>
<label><input ... /></label>
<label><input ... /></label>
<label><input ... /></label>
</div>
First of all, your inputs shouldn't be wrapped in labels, but that's a different argument.
The fastest way is probably:
$('input').click(function(){
var siblings = $(this).closest('div').find('input');
});
This will select your clicked input again too, though. If that's a problem, try:
$('input').click(function(){
var siblings = $(this).closest('div').find('input').not($(this));
});
If you were using correct markup so that the label tags preceded each input element, then your HTML would look like
<div>
<label for="input1" /><input id="input1" ... />
<label for="input2" /><input ... />
<label for="input3" /><input ... />
</div>
Then your jQuery code becomes way easier:
$('input').click(function(){
var siblings = $(this).siblings('input');
});
Well, assuming none of the elements in that markup have unique id's or class names, the most efficient selector you can use is a combination of tag names and the >, or first-child selector:
$("div > label > input");
$("div>label>input") I presume. Although you could give each input a common class and do $("input.class").
it depends. if the markup only consists of your fragment than:
$('input');
All modern broswers have a cache to tags.
If your looking for the inputs in within the div add an id to the div:
<div id="input_fields">
<label><input ... /></label>
<label><input ... /></label>
<label><input ... /></label>
</div>
and use this selector:
$('#iput_fields > label > input');
The id is important since it is the fastest possible query a browser can perform.
Seems like using class name better than using tag names without any parent. Here is the test for it for test your self.
Maybe more complex html structure give different results.