Passing an input value to a window.open method - javascript

I want in a form to pass the checked input radio button value to a window.open method. Bellow is what I try to use, but always is copied the value of the second input, regardless of what is selected. What is wrong here?
onsubmit="window.open(document.getElementByName('option').value);"
and
<input type="radio" name="option" value="http://example1.com" checked> daily
<input type="radio" name="option" value="http://example2.com"> weekly

If you really want to use onsubmit=, it can be done with querySelector and the :checked pseudoclass. (Note: Doesn't work in IE8 or earlier, but does in modern browsers back to IE9.)
onsubmit="window.open(document.body.querySelector('input[name=option]:checked').value)"
Live Example:
<form onsubmit="alert('Would have opened: ' + document.body.querySelector('input[name=option]:checked').value); return false;">
<input type="radio" name="option" value="http://example1.com" checked>daily
<input type="radio" name="option" value="http://example2.com">weekly
<input type="submit" value="Send">
</form>

You'll need to get the selected (checked) button's value.
If you don't need to support IE8 (which sadly still has significant market share), Jaromanda X's answer using :checked is the way to go.
If you do need to support IE8, you'll have to loop through to find out which radio button is checked:
function openSelected() {
var list = document.querySelectorAll("input[name=option]");
var i;
for (i = 0; i < list.length; ++i) {
if (list[i].checked) {
window.open(list[i].value);
break;
}
}
}
Then in your HTML
onsubmit="openSelected();"
...although I always advocate hooking up event handlers using addEventListener/attachEvent instead.
Live Example:
function openSelected() {
var list = document.querySelectorAll("input[name=option]");
var i;
for (i = 0; i < list.length; ++i) {
if (list[i].checked) {
alert("Would have opened: " + list[i].value);
break;
}
}
}
<form onsubmit="openSelected(); return false;">
<input type="radio" name="option" value="http://example1.com" checked>daily
<input type="radio" name="option" value="http://example2.com">weekly
<input type="submit" value="Send">
</form>

You need to select which option you want.
getElementsByName() returns an array. You need to select which element you want.
So you need to use:
onsubmit="window.open(document.getElementsByName('option')[0].value);"
for the first option, or:
onsubmit="window.open(document.getElementsByName('option')[1].value);"
for the second option

You could always just asign the input field an ID and call the ID instead of the name. For example:
onsubmit="window.open(document.getElementById('IDname').value);"
and
<input type="radio" id="IDname" name="option" value="http://example1.com" checked> daily
<input type="radio" name="option" value="http://example2.com"> weekly

Related

Jquery select from a collection of jquery objects which is checked

I haven't been able to find this answer. I don't know if I'm searching wrong or my lexicon is incorrect but I am trying to get the selected elements of a group of jquery radio buttons. Here is my JS code:
var hideFieldsBasedOnRadioButtonValue = function () {
var $employmentStatusRadioButtons = $(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']");
var displayOrHideRequiredFields = function ($radioButton) {
if ($radioButton.val() === "Full Time" || $radioButton.val() === "Part Time") {
$radioButton.closest("div.form-row").next(".required-input-when-yes").removeClass("d-none");
} else {
$radioButton.closest("div.form-row").next(".required-input-when-yes").addClass("d-none");
}
}
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
$employmentStatusRadioButtons.on("change", function () {
displayOrHideRequiredFields($(this));
});
}
This is a stripped down version of this function. I have a few more radio buttons that need to either hide or display additional fields depending on the radio button's value. What I'm having trouble with specifically is I want to trim this line down:
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
the $employmentStatusRadioButtons are a collection of jquery objects and I'm unable to figure out how to grab the selected one. Any help would be amazing.
Instead of using the same ".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']" selector on this line and on line 2 of the code I want to do something like
displayOrHideRequiredFields($employmentStatusRadioButtons:checked);
Now that won't work. The closest I've been able to get this to work is by doing the following;
displayOrHideRequiredFields($employmentStatusRadioButtons.selector + ":checked")
But I don't really like how that looks. We aren't using ES6 or else it would be awesome.
I haven't been able to find anything to help me in this regard. Does anyone know any methods specifically where I can do something like this?
You can use the jquery filter() function for filtering a variable with jQuery objects.
var $radios = $('[name=test],[name=test2]');
var $radiosFiltered = $radios.filter(':checked');
$radiosFiltered.each(function(){
console.log($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" value="1" checked>
<input type="radio" name="test" value="2">
<input type="radio" name="test" value="3">
<input type="radio" name="test2" value="4">
<input type="radio" name="test2" value="5" checked>
<input type="radio" name="test2" value="6">
You was so close, you need to use filter to get the checked elements from your collection :
$employmentStatusRadioButtons.filter(':checked');

Disabling textarea and input at the same time

I disable a textarea like in this code snippet:
function toggleDisabled(_checked,id) {
document.getElementById(id).readOnly = !_checked;
}
<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this.checked,'new_order')">
<textarea name="noa" id="new_order">FOOO</textarea>
<input type="text" name="noo" id="new_order">
Now I want input text to get disabled when I check the checkbox. So that both textarea and input:text will be disabled.
I tried to add the id that I used as ID for textarea but input:text and textarea are conflicted since readOnly is only for textarea.
So that I need a way tp say if textarea disable like this... , if input disable like this ...
id must be unique! Never use same id to more than one element.
the code below selects all elements that have the class new_order and then iterate through then disabling or enabling then. Take a look
function toggleDisabled(self) {
var inputs = document.getElementsByClassName('new_order');
for (var i = 0; i < inputs.length; i++){
inputs[i].disabled = self.checked;
}
}
<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this)">
<textarea name="noa" class="new_order">FOOO</textarea>
<input type="text" name="noo" class="new_order">
The problem arises when you use an id multiple times... ID's are supposed to be unique. If you use classes it should work:
function toggleDisabled(_checked, selector) {
document.querySelectorAll(selector).forEach((el) => {
el.readOnly = _checked;
});
}
<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this.checked,'.new_order')">
<textarea name="noa" class="new_order">FOOO</textarea>
<input type="text" name="noo" class="new_order">

form action to toggle a function?

<form action="" method="get" >
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
I have the following radio form and when I hit submit, I would like it to toggle some function in my js script. However, if I do something like:
document.getElementById("start").addEventListener('click',function ()...
Nothing works. I think I need something for the action tag, but I can only find examples that link to other websites/pages, which isn't what I want. Is toggling a function possible to do using the forms?
Thanks!
You're on the right track:
document.getElementById("start").addEventListener('click', function(e) {
e.preventDefault();
console.log('start!!');
const selected = document.querySelector('input[name="gender"]:checked');
console.log('you selected: ' + (selected ? selected.nextSibling.textContent : 'null'));
// your code here
});
<form>
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
You don't need an action or a method attribute. Make sure to use e.preventDefault() to prevent the form from submitting (redirecting the page) if you want to handle the form's values yourself.
You can define the submit function on form tag using onsubmit, Also this solution is accurate if you have multiple form tags on the same page.
function submitForm(form, event) {
event.preventDefault();
var val;
var radios = form.elements['gender'];
// loop through list of radio buttons
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) { // radio checked?
val = radios[i].value; // if so, hold its value in val
alert(val);
break; // and break out of for loop
}
}
alert("nothing selected");
return false;
}
<form onsubmit="return submitForm(this,event)">
<label><input type="radio" name="gender" id="male_sub" value="male">male</label><br>
<label><input type="radio" name="gender" id="female_sub" value="female">female</label><br>
<input type="submit" value="Let's Start!" id="start"><br>
</form>

Javascript adding values to radio buttons to input price

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

Enable/disable a form element after checking radio button checked states

I have ten or so questions with radio buttons. They all need to be set to true, before a user can move on to another level. If and only if these ten questions have be answered to true, I'd like to have one of the elements on the form be enabled for further editing. This, I can do on the server side, but don't know how to do it in JavaScript. Any help? Much appreciated. Thanks.
<div>
<label> First Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
<div>
<label> Second Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][researched]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][researched]" type="radio" value="false" />No</label>
</div>
<div>
<label> Third Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
This code extends to several more of questions.
I've been able to select radios by doing so:
var first_ten = $(':radio[name="project[person_attributes][is_complete_and_works]"][value=true], :radio[name="project[person_attributes][researched]"][value=true], etc…);
Now, I have no idea how to iterate over each and when I click on each radio, whether yes or no, I'd like to see the result for the element to be enabled. Any thoughts much appreciated.
Something like the following will do the job:
<script type="text/javascript">
function proceed(form) {
var el, els = form.getElementsByTagName('input');
var i = els.length;
while (i--) {
el = els[i];
if (el.type == 'checkbox' && !el.checked) {
form.proceedButton.disabled = true;
return;
}
}
form.proceedButton.disabled = false;
}
</script>
<form onclick="proceed(this);">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="submit" name="proceedButton" disabled>
</form>
Note that this is considered bad design as if javascript is not available or enabled, the user can never click the button. Better to deliver the form in a useful state and the, when submitted, use script to validate that the buttons are all checked and cancel the submit if they aren't.
Then at the server you can also check the state and only show the next page if the current one passes validation. If it doesn't, return the user to the first page.
That way neither you or the user care if the script works or not, the page still functions. Of course it might be a better experience if the script does work, but at least the choice isn't binary and it also gives you a simple fallback to support a very wide array of browsers with minimal effort.
So a better solution is:
<form onsubmit="reurn validate(this);" ...>
...
</form>
Then in the function:
function validate(form) {
// if validateion fails, show an appropriate message and return false,
// if it passes, return undefined or true.
}
And always validate at the server since you really have no idea what happened on the client.
Edit
Form controls don't need a name and ID, just use a name. In a radio button set, only one control can be checked, you can't check all of them.
It seems to me that what you are trying to do is to see if at least one radio button has been checked in each set. You can do that based on the code above and selecting each set as you encounter it, e.g.
function validateForm(form) {
// Get all the form controls
var control, controls = form.elements;
var radios = {};
var t, ts;
// Iterate over them
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
// If encounter a radio button in a set that hasn't been visited
if (control.type == 'radio' && !radios.hasOwnProperty(control.name)) {
ts = form[control.name];
radios[control.name] = false;
// Check the set to see if one is checked
for (var j=0, jLen=ts.length; j<jLen; j++) {
if (ts[j].checked) {
radios[control.name] = true;
}
}
}
}
// Return false if any set doesn't have a checked radio
for (var p in radios) {
if (radios.hasOwnProperty(p)) {
if (!radios[p]) {
alert('missing one');
return false;
}
}
}
}
</script>
<form onsubmit="return validateForm(this);">
<input type="radio" name="r0">
<input type="radio" name="r0">
<br>
<input type="radio" name="r1">
<input type="radio" name="r1">
<br>
<input type="reset"><input type="submit">
</form>
Note that your form should include a reset button, particularly when using radio buttons.

Categories

Resources