How to get data attribute from radio button with JavaScript? - javascript

I want to get the data-price value from radio button which is checked. I tried something like that:
<input type="radio" name="vehicletype" id="vehicletype" value="{{$vehicletypeData->id}}" data-price="{{$vehicletypeData->km_rate}}" required="">
var vehicleTyp=document.getElementById("vehicletype");
var vetselindx=vehicleTyp.options[vehicleTyp.selectedIndex];
var prikm=vetselindx.getAttribute("data-price");
But this does not work. How can I solve this issue?

document.getElementById("vehicletype");
This gets the element with that id. The single element with that id. Multiple elements in a document cannot share an id.
vehicleTyp.options
Select elements have options. Radio buttons do not.
To find the checked element you should:
Get all the radio buttons. Consider getElementsByName
Loop over them until you find one where the checked property is true
Once you have found the element you are looking for you can use getAttribute("data-price"); or the dataset property.

You can reference the custom data- attributes of an element like so:
const el = document.getElementById("vehicletype");
const price = el.dataset.price;
For more information see the MDN docs on using data attributes.
Note: If you have a second dash in the attribute name e.g. data-price-new the dataset object property will reflect this in camelcase. dataset.priceNew

Working code, using getElementsByName
<input class="form-check-input" type="radio" data-type="one-time" name="payment-radio-btn" value="200" id="flexRadioDefault1" checked />One Time
<input class="form-check-input" type="radio" data-type="two-time" name="payment-radio-btn" value="300" id="flexRadioDefault1"/>Two time
<p> <button onClick="performAction()">Submit</button> </p>
function performAction(){
var amount = 0;
var type = '';
var radios = document.getElementsByName('payment-radio-btn');
for (var radio of radios) {
if (radio.checked) {
amount = radio.value;
type = radio.getAttribute("data-type");
}
}
alert(type)
}
Codepen-link

Related

Get the text from label of Radiobutton

I have a couple of radio button below. I want to get the text from the radio button I have chosen. For example: House Espresso or Guest Espresso. I have tried to use getElementsByName and for loop to get the checked value but it seems to return nothing.
Here is my HTML code:
<div class="type">
<p>Type<p>
<input type="radio" id="houseEspresso" name="singleEspresso" checked="checked"onclick="addProduct(this)">
<label for="houseEspresso">House Espresso</label><br>
<input type="radio" id="guestEspresso" name="singleEspresso" onclick="addProduct(this)">
<label for="guestEspresso">Guest Espresso</label><br>
</div>
And here is my Javascript code:
var type = document.getElementsByName("singleEspresso")
for (var i=0; i<type.length; i++){
if(type[i].checked){
var title_type=type[i].innerText
console.log(title_type)
}
}
Can anyone give me an idea to fix it? Thank you!
The problem is that you're trying to get innerText from the <input>, which has none. You need to get the <label>'s text:
for (var i=0; i<type.length; i++){
if(type[i].checked){
var title_type=type[i].nextElementSibling.innerText
console.log(title_type)
}
}
You need to find a checked input, for that you can use :checked css selector. Then you can pick any value from input DOM element which ties it to label (in your case it's id). And basing on the id you can find corresponding label.
const selectedRadioInput = document.querySelector('[name=singleEspresso]:checked');
const inputId = selectedRadioInput.id;
const label = document.querySelector(`[for=${inputId}]`);
console.log(label.innerText);
Working demo: https://jsfiddle.net/yo18mx9k/2/
You can set a value to input radio: <input type="radio" value="1">
Then just get the buttons and see which one is checked, like this:
let house = document.getElementById('houseEspresso');
let guest = document.getElementById('guestEspresso');
if (house.checked) {
console.log(house.value);
} else if (guest.checked) {
console.log(guest.value);
}
However, I would recommend that you take a look at jQuery so you can make it easier:
$("input[name='singleEspresso']:checked").val();

Calculations with Radio Buttons

I am trying to create this JavaScript calculation with radio buttons. So If the user Checks the "delivered to home address" then the value of £5.99 will be added into the total box, but if the user selects the other radio button, then no price will get shown. I am pretty new to JavaScript so I may have a few errors, but i'd be grateful if you could help me out
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
Total <input type="text" name="total" size="10" readonly>
JavaScript
let totalPrice = 0;
var RadioBtn = document.getElementById ('input[name=deliveryType]');
radioBtn.addEventListener("click", function() {
if(radioBtn.clicked) {
totalPrice += parseFloat(radioBtn.dataset.price)
total.value = " + totalPrice;
}
}
Here are my observations from the code provided:
The radioBtn variable was declared with Pascal Case (first letter
upper case) so it won't be referenced in the code since the other
lines use camelCase(starts with Lower case). change to camelCase and
stick with it through out the code.
Your selector - getElementById is used for Ids and it would return one
element, since you are passing a query selector
'input[name=deliveryType]' instead the code will not find the
element you are looking for
Since you are looking to add click events to the radio buttons, you can
use getElementsByName and provide the name of the radio
buttons. Then iterate through the resulting elements to apply the
click event... that way the click will be called for both radio
buttons.
No need to check if clicked inside the click event, you already know it
will be called when clicked only, instead you can add the
event parameter to get the click target and its information to apply
it as needed.
Example:
let totalPrice = 0;
let radioBtns = document.getElementsByName('deliveryType');
let totalEl = document.getElementsByName ('total')[0];
radioBtns.forEach(function(element, index){
element.addEventListener("click", function(event){
totalPrice += parseFloat(event.target.dataset.price); //remove += if the price should be the same everytime, replace with = or it will add the number to the total when clicked
totalEl.value = totalPrice + " totalPrice";
});
});
https://jsfiddle.net/dn4x7oy9/8/

Check one checkbox when other is selected [duplicate]

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

How to receive values from 'HTML form' to a javascript code? [duplicate]

This question already has answers here:
How can we access the value of a radio button using the DOM?
(12 answers)
Closed 9 years ago.
The form includes Radio, Select, Input etc..
var variable = document.getElementById('anyId').value;
It works fine with input element, but with radio button element it's not working as desired!
On my HTML page (for radio) the code looks something like this,
<input type="radio" id="radioValue" name="radio" value="2">Radio_1
<input type="radio" id="radioValue" name="radio" value="1">Radio_2
and in the script
var radio_value = document.getElementById('radioValue').value;
radio_value is always equal to 2, it doesn't matter whether you select radio_1 or radio_2.
By using getElementsByName
var selectedradio;
var radios = document.getElementsByName("radio");
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked == true) {
alert(radios[i].value);
selectedradio = radios[i].value;
}
}
ID's must be unique. So you should change your code to this:
<input type="radio" id="radioValue1" name="radio" value="2">Radio_1
<input type="radio" id="radioValue2" name="radio" value="1">Radio_2
And then you can get those values by:
var radio_value1 = document.getElementById('radioValue1').value;
var radio_value2 = document.getElementById('radioValue2').value;
//or
var radio_value=document.querySelector('input[name="radio"]:checked').value;
// in this last case you don't need even to have id's in the buttons
Otherwise trying to read two values with the same ID will give you just the first one of them.
Pure javascript for most modern browsers.(works also in ie 9)
if you have just one form and only one group of radio's use querySelector
it's the new proper way.
var radio_value=document.querySelector('input[type="radio"]:checked').value
You can also easely extend it if you have multiple radio groups and forms.
var radio_value=document.querySelector('#YOURFORM input[name="radio"]:checked').value

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

Categories

Resources