I have this code:
<input type="radio" name="pay" id="payid" value="banktransfer"> Bank Transfer <br/>
<input type="radio" name="pay" id="payid" value="paypal"> PayPal <br/> <br/>
I try:
var sample = $('#payid').val()
alert(sample);
Why I have still banktransfer? (regardless of the selected input)?
The id must be unique. Radios need the same name for their on-off functionality to work, but each must have a unique id. You could, for instance, have "payid1" and "payid2"
The ID attribute must be unique across the page. In your case jQuery is just picking the first element with that ID and returning that value. This code will get you the selected value.
jQuery("input[name=pay]:checked").val();
Try
var sample = $("[name=pay]:checked").val()
You need to specify which one of the radio buttons you want, you can get the correct one (the checked one) by using the :checked selector. You also need to use the name attribute selector, because id needs to be unique and JQuery will only ever return the first match.
This should work for you:
var sample = $('[name="pay"]:checked').val();
alert(sample);
Here is a working example
Related
I'm looking to set multiple values and checkboxes on a webpage using JS.
I'm able to do values using
document.querySelector('input[name="date"]').value = '1/1/2000';
document.querySelector('form').submit();
...that's simple enough. There are multiple checkboxes that may or may not need to be checked. What is the process to check a box through the console? Here is a sample of one of them when it is checked:
input id="FormView1_cb_EXAMPLE" type="checkbox"
name="FormView1$cb_EXAMPLE" checked="checked"
You can do this by targeting the checked attribute of the item after selecting it with either querySelector or getElementByID. Then simply set it to true for checked.
document.querySelector('#steve').checked=true
<input id="steve" type="checkbox">
If you need to do it to multiple and they all have the same class name, you can use querySelectorAll and a forEach/for loop and set each one to true (checked) using that method. (this would only work if your list of which ones need to be checked conditionally is constant)
I hope your job looks
var input = document.querySelector('#FormView1_cb_EXAMPLE').checked;
console.log(input)
<input id="FormView1_cb_EXAMPLE" type="checkbox">
Currently, I am trying to learn js.
At this moment, I can make some simple functional scripts. But whenever I want user input, I still have to us a prompt, which can become quite annoying.
Therefore, I want to use HTML boxes for user input.
I put the box in HTML like this:
<FORM>
<INPUT type="button" value="Fill Me In" name="box1">
</FORM>
But how do I call the input in javascript then?
Thanks in advance.
You can do as follow :
<FORM>
<INPUT type="button" value="Fill Me In" name="box1" id="txt">
</FORM>
Javascript :
var txtval=document.getElementById("txt").value;
or :
you can create custom dialog and show it using javascript or jquery(best option)
For more about dialog refer This link
There are various methods to get input textbox value:
Method 1:
document.getElementById('textbox_id').value to get the value of desired box
Eg. document.getElementById("searchTxt").value;
*Note : Method 2,3,4 and 6 returns a collection of elements called NodeList, so use [whole_number] to get the desired occurence, for first element use [0] and for second one use 1 and so on...*
Method 2:
Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live Nodelist
Eg. 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 nodelist
Eg. document.getElementsByTagName("input")[0].value; ,
if this is the first textbox in your page.
Method 4:
document.getElementsByName('name')[whole_number].value
Eg. document.getElementsByName("searchTxt")[0].value;
if this is the first textbox with name 'searchtext' in your page.
Method 5:
Use powerful document.querySelector('selector').value which uses CSS selector to select element
Eg. 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 CSS selector to select elements but it returns all elements with that selector as a static nodelist.
Eg. 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
You can use window.openDialog to open a window as a dialog:
var retValues = { box1: null };
var win = openDialog("your_form.html", "dlg", "modal", retVals);
alert(retValues.box1);
Then your dialog:
<FORM onsubmit="window.arguments[1].box1 = document.getElementById('txt').value; close();">
<INPUT type="button" value="Fill Me In" name="box1" id="txt">
</FORM>
My problem today could be rather simple. I am trying to obtain all required elements inside of a form for which there is no text (they are of type input, text). Here is my JS:
var inputs = $('#form').find(':input');
if(inputs.filter('[required] [value=""]').first().focus().length)
//do something
This is the element in the HTML:
<input type="text" name="title[]" id="name_" required />
I should add that this input element is being added dynamically by javascript, meaning, it's appended after a certain action has taken place.
The true problem is that the code inside of the if statement is never true even when I don't type a value for the given text field.
Any help is appreciated.
The value attribute of an input tag is not the same thing as the value property of an input element. The first one happens to be in the HTML, gets parsed in the DOM and acts as the defaultValue. The latter one is the dynamic value which represents the currently entered input. See also .prop() vs .attr()
Your element does not even have a value attribute, so it will never match the selector. Instead, you will need to use a filter function that checks the properties:
inputs.filter(function() {
return this.required && this.value=="";
// equivalent: $(this).prop("required")
// and $(this).prop("value") or $(this).val()
})
If you mean to select required inputs that are empty, your selector is wrong. The space represents ancestor relationship, parent/children:
if (inputs.filter('[required][value=""]').length) { // Element is `required` and empty
....
}
There are 2 issues with your code.
('[required] [value=""]')
Supposed to be
('[required][value=""]')
And with the above selector you can never select the input below
<input type="text" name="title[]" id="name_" />
as it has no value attribute in the first place. Also required attribute is missing
The inputs that would match your selector would be of this signature
<input type="text" required="true" value="" name="title[]" id="name_" />
Check Fiddle
When I handle HTML form elements with jQuery, I always end up with an ugly mix of jQuery syntax and plain JavaScript like, e.g.:
function doStuff($combo){
if( $combo.get(0).options[$combo.get(0).selectedIndex].value=="" ){
var txt = "";
}else{
var txt = $combo.get(0).options[$combo.get(0).selectedIndex].text;
}
var $description = $combo.closest("div.item").find("input[name$=\[description\]]");
$description.val(txt);
}
Are there standard jQuery methods to handle typical operations on elements like <select>, <input type="radio"> and <input type="checkbox">?
With typical, I mean stuff like reading the value of the selected radio button in a group or replacing elements in a selection list. I haven't found them in the documentation but I admit that method overloading can make doc browser kind of tricky.
Update
Thanks everyone. Once in the right track, I figured out myself the rest of the stuff. E.g., I can handle a <select> list like any other DOM tree:
$("select")
.empty()
.append('<option value="">(Pick one)</option><option value="a">Option A</option><option value="b">Option B</option>');
Yes, you should be able to simplify your code a lot. Here are a few examples of working with form elements:
<input type="text">
$(':text') // select all text boxes
$('input#example').val(); // gets value of a text box
<input type="checkbox">
$(':checkbox') // selects all checkboxes
$('input.example:checked') // selects all ticked checkboxes with class 'example'
$('#example').is(':checked'); // true if checkbox with ID 'example' is ticked
<input type="radio">
$(':radio') // selects all radio buttons
$(':radio:checked').each( function() {
$(this).val(); // gets value of each selected radio button
});
$('input:radio[name="asdf"]'); // gets particular group of radio buttons
<select>
$('select#example').change( function() {
// this part runs every time the drop down is changed
$(this).val(); // gets the selected value
});
See also http://api.jquery.com/category/selectors/form-selectors/ for more selectors.
Since you want the text and not the value, use .text() for that <option> (find it using the :selected selector), like this:
function doStuff($combo){
var txt = $combo.children("option:selected").text();
$combo.closest("div.item").find("input[name$=\[description\]]").val(txt);
}
If you wanted the value part of <option value="4" selected>Four</option> then you could use .val(), like this:
var val = $combo.val();
For <select> elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).
For selects you can use the val() method. In case of multiple select the val() method returns an array of the selected options.
For checkboxes and radio you can grab all the selected checkboxes using the :checked selector.
You'll find all the details as well as examples at the jQuery site : http://api.jquery.com/val/
For Select elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).
Ignore formatting....i havent done that..;)
I have 2 radios:
<input id="a_15_0" type="radio" value="abc" name="a_15"/>
<input id="a_15_1" type="radio" value="xyz" name="a_15"/>
Both are unselected. I have only the name of the radio, i.e a_15, but not the IDs.
1) How can I get the value of the selected option of this radio? E.g if the user clicked 'xyz', how can I get it? Right now I'm using:
var val=$('[name="a_15"]').val();
Which always gives abc even when xyz is selected.
2) How can I get xyz to be selected through javascript, without knowing the ID of the radio which says xyz? Doing:
$('[name="a_15"]').val('xyz');
Changes the value of both radios to xyz rather than selecting the one whose value had been xyz.
Do I need to use document.myForm.a_15.value? Would that work consistently?
1)
try
var val = $('input[name=a_15]:checked').val();
jQuery docs on checked pseudo-class
2) the only solution I found is
$('input[name=a_15][value=xyz]').get(0).checked=true
Have you tried using the val() in conjunction with the :checked selector?
$('[name="a_15"]:checked').val();
As for setting the selection based on the value, you may have to perform a multiple attribute tests?
$('[name="a_15"][value="xyz"]').get(0).checked = true;
There are many ways of selectors in jQuery; id, class, etc..I believe this will do the job, not tested:
var val= $("input[name=a_15]:checked").val();
if you know the name of the form then this will definitely do it
var val= jQuery('#radio_form input:radio:checked').val();
you have the correct code here:
to run
to edit
the correct form is:
$("input[name='a_15']:checked").val();
as you can test using the links above