how to get the value of a radio button [duplicate] - javascript

This question already has answers here:
How to get value of selected radio button?
(30 answers)
Closed 6 months ago.
I have a purchase order in which I would like to be able to retrieve the value of the button so that I can send it by POST
But it doesn't work I get this error when I validate the data with the command button
Uncaught TypeError: document.getElementByName is not a function
here is the radio button syntax and processing in ajax
<fieldset>
<div>
<input type="radio" id="huey" Name="promotion" class="promotion" value="huey"checked
>
<label for="huey">Huey</label>
</div>
<div>
<input type="radio" id="dewey" Name="promotion" class="promotion" value="dewey">
<label for="dewey">Dewey</label>
</div>
<div>
<input type="radio" id="louie" Name="promotion" class="promotion" value="louie">
<label for="louie">Louie</label>
</div>
</fieldset>
function commander(nom, prenom, adresse,detail_livraison,promotion) {
$.ajax({
url: 'mail.php',
type: 'POST',
data: 'nom=' + nom + '&prenom=' + prenom + '&adresse=' + adresse + '&detail_livraison=' + detail_livraison + '&promotion=' + promotion ,
dataType: 'html',
success: function(reponse) {
if(reponse == "1") {
//MonPanier.clearpanier();
afficherpanier();
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
$('#mymodal').modal('show');
}
if(reponse == "0-1") {
$('#mymodal_erreur_1').modal('show');
}
if(reponse == "0-2") {
$('#mymodal_erreur_2').modal('show');
}
if(reponse == "0-3") {
$('#mymodal_erreur_3').modal('show');
}
if(reponse == "0-4") {
$('#mymodal_erreur_4').modal('show');
}
if(reponse == "0-5") {
$('#mymodal_erreur_5').modal('show');
}
}
});
}
$('#commander').click(function() {
var nom = document.getElementById("nom").value;
var prenom = document.getElementById("prenom").value;
var adresse = document.getElementById("adresse").value;
var detail_livraison = document.getElementById("livraison-detail").innerHTML;
var promotion = document.getElementByName("promotion").innerHTML;
commander(nom, prenom, adresse,detail_livraison,promotion,);
});

As I see you are already using jQuery, then why not do something like this -
let promotion = $('input[name="promotion"]:checked').val()
You can read more about it here in the doc

const log = data => console.log(JSON.stringify(data));
let $promo = $('.promotion').val();
const all = document.forms.main.elements;
let promo = all.promotion.value;
log($promo);
log(promo);
<form id='main'>
<fieldset>
<div>
<input type="radio" id="huey" name="promotion" class="promotion" value="huey" checked>
<label for="huey">Huey</label>
</div>
<div>
<input type="radio" id="dewey" name="promotion" class="promotion" value="dewey">
<label for="dewey">Dewey</label>
</div>
<div>
<input type="radio" id="louie" name="promotion" class="promotion" value="louie">
<label for="louie">Louie</label>
</div>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Alert in Javascript

On my order site, I have 2 options: pick up and delivery.
When choosing pick up, nothing happens, but when choosing delivery, the delivery address will appear for the user to fill in.
I want to use JS to notify you that you need to enter your shipping address only I you tick the delivery box.
Thank you.
/*Notify when information is invalid.*/
function validate() {
var pickup = document.getElementById("pickup").checked;
var delivery = document.getElementById("delivery").checked;
var deladd = document.getElementById("delivery_address").value;
var biladd = document.getElementById("billing_address").value;
if ((pickup == "") && (delivery == "")) {
errMsg += "Select an option. \\n";
}
if ((deladd == false) && (deladd == "")) {
errMsg += "Delivery address can not be empty.\\n";
if (errMsg != "") {
alert(errMsg);
result = false;
}
return result;
}
function init() {
var regForm = document.getElementById("form");
regForm.onsubmit = validate;
}
window.onload = init;
<div class="box">Select an option:
<input type="radio" id="pickup" name="option" value="pickup" class="radio" onclick="hideAddress()">
<label for="pickup" class="check">Pick Up</label>
<input type="radio" id="delivery" name="option" value="delivery" class="radio" onclick="showAddress()">
<label for="delivery" class="check">Delivery</label>
</div><br>
<div class="show" id="show">
<!--Delivery address.-->
<input type="text" placeholder="delivery address:" class="box" id="delivery_address" name="delivery_address">
<!--Check the same as the delivery address or not.-->
<label for="checkbox"> billing address same as delivery address</label>
<input type="checkbox" id="same_address" name="same_adsress_or_not" value="same_adress" onclick="autoFill()">
</div>
/*Notify when information is invalid.*/
function validate() {
var pickup = document.getElementById("pickup").checked;
var delivery = document.getElementById("delivery").checked;
var deladd = document.getElementById("delivery_address").value;
var biladd = document.getElementById("billing_address").value;
if ((pickup == "") && (delivery == "")) {
errMsg += "Select an option. \\n";
}
if ((deladd == false) && (deladd == "")) {
errMsg += "Delivery address can not be empty.\\n";
if (errMsg != "") {
alert(errMsg);
result = false;
}
return result;
}
}//closed here
function init() {
var regForm = document.getElementById("form");
regForm.onsubmit = validate;
}
window.onload = init;
<div class="box">Select an option:
<input type="radio" id="pickup" name="option" value="pickup" class="radio" onclick="hideAddress()">
<label for="pickup" class="check">Pick Up</label>
<input type="radio" id="delivery" name="option" value="delivery" class="radio" onclick="showAddress()">
<label for="delivery" class="check">Delivery</label>
</div><br>
<div class="show" id="show">
<!--Delivery address.-->
<input type="text" placeholder="delivery address:" class="box" id="delivery_address" name="delivery_address">
<!--Check same as delivery address or not.-->
<label for="checkbox"> billing address same as delivery address</label>
<input type="checkbox" id="same_address" name="same_adsress_or_not" value="same_adress" onclick="autoFill()">
</div>
In your code, you appear to have forgotten to close the function validate()'s
curly brackets (never closed the bracket "{").
Always remember to close your brackets.
Hope this helps :).
(still shows errors because incomplete code)

One submit button works on my form the other one refreshes the website while updating the url

Im trying to make a quiz using forms and the top submit button works perfectly while the bottom button does not work it ends up refreshing the page and it says the field selected in the address bar this is for a project for college and im a beginner to JavaScript if someone could help me out and explain how it works that would be great I understand how the script works with one from and one button and what the code does but im confused when it comes to 2 forms
var form = document.querySelector("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
form.addEventListener("submit", function(event) {
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText = output;
event.preventDefault();
pointsAdd();
}, false);
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<header>
<ul class="navbar">
<li>Home</li>
<li>Poland</li>
<li>Russia</li>
<li>Uzbekistan</li>
</ul>
</header>
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log">
</pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>
You have TWO forms. so you need an event handler for each
You have ONE log element so I suggest you might want to append the result
Move the preventDefault to the top of the handler to not have a later error submit the form
NOTE: Header ALSO goes in the body (but is irrelevant to your question).
var forms = document.querySelectorAll("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
forms.forEach(form => form.addEventListener("submit", function(event) {
event.preventDefault();
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText += output;
pointsAdd();
}))
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log"></pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>

I need to write values from radio button to console (JS const)

let opinions = [];
if (localStorage.myTreesComments) {
opinions = JSON.parse(localStorage.myTreesComments);
}
console.log(opinions);
const myFrmElm = document.getElementById("opnFrm");
myFrmElm.addEventListener("submit", processOpnFrmData);
function processOpnFrmData(event) {
const nopName = document.getElementById("menoapriezvisko").value.trim();
const nopEmail = document.getElementById("email").value.trim();
const nopUrl = document.getElementById("url").value.trim();
const nopComm = document.getElementById("komentar").value.trim();
const nopStar1 = document.getElementById("star-rating").value.trim();
const nopStar2 = document.getElementById("star-rating2").value.trim();
const nopScale = document.getElementById("scale-rating").value.trim();
const nopWillReturn = document.getElementById("willReturnElm").checked;
if (nopName == "" || nopEmail == "" || nopUrl == "" || nopComm == "") {
window.alert("Prosím, zadajte všetky údaje.");
return;
}
const newOpinion = {
name: nopName,
email: nopEmail,
url: nopUrl,
comment: nopComm,
gdpr: nopWillReturn,
created: new Date()
};
console.log("Nový názor návštevníka:\n " + JSON.stringify(newOpinion));
opinions.push(newOpinion);
localStorage.myTreesComments = JSON.stringify(opinions);
//4. Notify the user
window.alert("Tvoj názor bol uložený! Pre viac info nahliadni do konzole.");
console.log("Nový názor bol pridaný!");
console.log(opinions);
//5. Reset the form
myFrmElm.reset();
}
<form id="opnFrm">
<label for="menoapriezvisko">Meno a priezvisko</label>
<input type="text" id="menoapriezvisko" name="menoapriezvisko">
<label for="email">Kontaktný email</label> <input type="email" id="email">
<label>1. Celková spokojnosť s dizajnom a funkcionalitou stránky ?</label><br>
<span class="star-rating">
<input type="radio" name="rating1" value="1"><i></i>
........................
<input type="radio" name="rating1" value="5"><i></i>
</span>
<div class="clear"></div>
<hr class="survey-hr">
<label>2. Celková spokojnosť s obsahom.</label><br>
<span class="star-rating2">
<input type="radio" name="rating2" value="1"><i></i>
..........................
<input type="radio" name="rating2" value="5"><i></i>
</span>
<div class="clear"></div>
<hr class="survey-hr">
<label style="color: red;"><b>3. Celkové hodnotenie stránky (1-10)</b></label>
<span class="scale-rating">
<label value="1">
<input type="radio" name="rating" >
<label style="width:100%;"></label>
</label>
<label value="2">
<input type="radio" name="rating" >
<label style="width:100%;"></label>
</label>
..................
<label value="10">
<input type="radio" name="rating" value="10">
<label style="width:100%;"></label>
</label>
</span>
<div class="clear"></div>
<input style="background:#43a7d5;color:#fff;padding:12px;border:0" type="submit" value="Odoslať">
<button type="submit">Odošli</button>
<input style="background:#43a2d1;color:#fff;padding:12px;border:0" type="reset" value="Resetuj">
</form>
</div>
</article>
I need to write values from 3 spans of radio buttons to my JS script into const Opinions.
In first 2 spans I have star rating from 1-5 and in the third span I have points (1-10).. I need to read these values and write them into my script. Please if u can help me i would be really pleased. It is hard for me.
I am using jQuery and Javascript.
Thanks for any help.

How to use global variable so i can use it on my javascript module

i want to get all of this input values to my budget app
but i have problem to get values of the radio button because it says its undefined. i create global function to get by radio button value. but the others is in javascript module.
https://jsfiddle.net/8k3gw7ty/
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
Actually there was no default value for your val variable. Since val will only get value when you click on the checkbox (according to your code).
Also you were returning val which isn't necessary. I've also removed the budgetController.
Hope this'll help.
let val = 'inc'; // default value
function getButtonValue() {
var type = document.getElementsByName("type");
if (type[0].checked) {
val = type[0].value
} else if (type[1].checked) {
val = type[1].value
}
}
const domController = (function() {
return {
getInput: function() {
return {
type: val,
description: document.querySelector(".input_description").value || 0,
value: parseFloat(document.querySelector(".input_value").value) || 0
}
}
}
})();
const controller = (function( UI) {
var ctrlAddItem = function() {
var input = UI.getInput();
console.log(input);
}
document.querySelector(".addbtn").addEventListener("click", ctrlAddItem)
document.addEventListener("keypress", function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
})( domController);
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
<button><i class="fas fa-check addbtn">Save</i></button>

use implode and ajax to insert checkbox values

i want to insert my checkbox values, i dont know how to take all the values using ajax and use implode to insert them in one row.
// this is my javascript where i take the data ,
function saveData() {
var modsubj = $('#modalsubject').val();
var modsect = $('#modalsection').val();
var modday = $('#modalday').val();
var modstart = $('#modalstarttime').val();
var modend = $('#modalendtime').val();
var moduser = $('#userID').val();
$.ajax({
type: "POST",
url: "modal.funcs.php?p=add",
data: "subj=" + modsubj + "&sect=" + modsect + "&day=" + modday + "&start=" + modstart + "&end=" + modend + "&user=" + moduser
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="M">Monday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="T">Tuesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="W">Wednesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="Th">Thursday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="F">Friday
</label>
</div>
this is my php function, i used the implode function so that i can insert the data on one row.
$page = isset($_GET['p'])?$_GET['p']:'';
if($page=='add'){
foreach ($_POST['day'] as $key => $value) {
$subj = $_POST['subj'];
$sect = $_POST['sect'];
$day = implode("",$_POST['day']);
$strTime = $_POST['start'];
$endTime = $_POST['end'];
$user_id = $_POST['user'];
}
$auth_user->createSchedule($subj,$sect,$day,$strTime,$endTime,$user_id);
$schedRow = $auth_user->readSchedule();
} else if ($page=='edit') {
}
Here is how to send a list to the server
You can explode the day to get an array of days
To add more items, add a comma and more key values:
data: { day: modday.join(","),
subj:$('#modalsubject').val() // no comma on the last
}
$(function() {
$("#save").on("click", function() {
saveData();
});
});
function saveData() {
var modday = [];
$('.modalday:checked').each(function() {
modday.push(this.value);
});
console.log(modday);
$.ajax({
type: "POST",
url: "modal.funcs.php?p=add",
data: { day: modday.join(",") }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="M">Monday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="T">Tuesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="W">Wednesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="Th">Thursday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="F">Friday
</label>
</div>
<button id="save">Save</button>
I tried this myself, and I think most of the action can occur in your saveData function, not in PHP.
I'm assuming you will change your ids to a class instead, as id's should be unique:
<input type="checkbox" class="modalday" name="modalday[]" value="M">Monday
Check this out:
function saveData() {
var modsubj = $('#modalsubject').val();
var modsect = $('#modalsection').val();
var moddayAll = document.getElementsByClassName('modalday');
var modday = [];
for (let i = 0; i < moddayAll.length; i++) {
if (moddayAll[i].checked) {
modday.push(moddayAll[i].value);
}
}
var modstart = $('#modalstarttime').val();
var modend = $('#modalendtime').val();
var moduser = $('#userID').val();
var add = 'add';
$.post("modal.funcs.php", {p:add, subj:modsubj, sect:modsect, day:modday.join(","), start:modstart, end:modend, user:moduser},
function( data ) {
// do whatever you want with data returned from modal.funcs.php
}
);
};
I just used vanilla JavaScript to select all the modalday elements, then loop through them and add the values (M, T, W, etc...) of the ones that are checked to the modday array:
var moddayAll = document.getElementsByClassName('modalday');
var modday = [];
for (let i = 0; i < moddayAll.length; i++) {
if (moddayAll[i].checked) {
modday.push(moddayAll[i].value);
}
}
Then, since you are using the POST method anyway, I used JQuery's .post(), and passed the 'p' param along with the data, instead of in a query string. You'll notice this is where the modday array is turned to a string with the join() call as well:
var add = 'add';
$.post("modal.funcs.php", {p:add, subj:modsubj, sect:modsect, day:modday.join(","), start:modstart, end:modend, user:moduser},
function( data ) {
// do whatever you want with data returned from modal.funcs.php
}
);
Then, in modal.funcs.php, you can just get the values from the $_REQUEST variable and pass them to your functions:
<?php
$page = $_REQUEST['p'];
if ($page == 'add') {
$subj = $_REQUEST['subj'];
$sect = $_REQUEST['sect'];
$day = $_REQUEST['day'];
$strTime = $_REQUEST['start'];
$endTime = $_REQUEST['end'];
$user_id = $_REQUEST['user'];
$auth_user->createSchedule($subj,$sect,$day,$strTime,$endTime,$user_id);
$schedRow = $auth_user->readSchedule();
} else if ($page=='edit') {
}
$_REQUEST['day] will be a comma-separated string of the values of the checkboxes that were checked. If you need to do further processing of the array here, you can add another step to do so.

Categories