How can i retrieve this value using an alert box? - javascript

On my website i have a html file with the following configuration:
<script>
window.Conf.page = window.Conf.page || {};
$.extend(Conf.page, {"newNotifications":false,"userId":"125"}
</script>
In the same page i need to retrieve the value of userId using a script and display it into an alert box. I tried using this script:
<script>
alert(document.getElementsByName('userId'))
</script>
But i'm getting [object NodeList] inside the alert box.
What code could i use to get the value of userId inside the alert box?

Try like this:
alert(window.Conf.page.userId);

<script>
window.Conf.page = window.Conf.page || {};
var json = $.extend(Conf.page, {"newNotifications":false,"userId":"125"});
alert(json.userId);
</script>
or
<script>
window.Conf.page = window.Conf.page || {};
Conf.page = $.extend(Conf.page, {"newNotifications":false,"userId":"125"});
alert(Conf.page.userId);
</script>

This gets the value property of the element in the node list, the node list is a list of all the nodes with the name property matching the one you pass in, in the off chance you had two input fields with the name property being the same their index would be 0 and 1 respectively.
document.getElementsByName('userId')[0].value

I think what you are looking for is the getElementById if an looking for an HTML tag, or in your case here simply window.Conf.page.userId to get the value.
window.pageConf = window.pageConf || {};
$.extend(pageConf, {"newNotifications":false,"userId":"125"});
function onTestClick() {
var a = document.getElementsByName('userId');
document.getElementById('myLabelId').innerText = a.length;
// Result: 0
document.getElementById('myLabelId').innerText += " " + window.pageConf.userId;
// Result: 125
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="onTestClick()">Test</button><br/><br/>
<label id="myLabelId"></label>
Having said that, let's talk about "name" in a tag.
getElementsByName returns an array because Name is not unique to an element. Name is used for mainly 2 things:
For postback: When submitting a form, the value of input is posted with the "name" in the tag. For example:
Comments: <input id='myUniqueLocalId' name='comments' />
To group radio buttons or checkboxes together. Small example:
function onTestClick() {
var q1 = document.getElementsByName('q1');
document.getElementById('myLabelId').innerText += " " + q1.length + " " + q1[0].value + " " + q1[1].value;
// Result: 2 Yes No
}
Question 1:
<input type="radio" id="Yes" name="q1" value="Yes" checked>
<label for="Yes">Yes</label><be>
<input type="radio" id="No" name="q1" value="No">
<label for="No">No</label><br>
Question 2:
<input type="radio" id="Yes" name="q2" value="Yes">
<label for="Yes">Yes</label><be>
<input type="radio" id="No" name="q2" value="No" checked>
<label for="No">No</label><br>
<button onclick="onTestClick()">Test</button><br/><br/>
<label id="myLabelId"></label>

Related

Javascript how to change radio button label text?

I want to change the text of the label which is associated with the radiobutton id="male". I have tried various ways to do it, but i can't make it work. I want to change the text "Male" in the label associated to the radio button.
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
<input type="button" value="Submit" onclick = test()>
<script>
function test()
{
var r = document.getElementById("male");
r.nextSibling.data = "adaS";
// r.nextSibling.nodeValue = "adaS"; // have tried all these ways
// r.childNodes[0].value= "adaS";
// r.childNodes[0].innerHTML= "adaS";
// r.parentNode.childNodes[1].innerHTML= "adaS";
}
</script>
please suggest some working way to change the text "Male" in the label.
You can use
var r = document.getElementsByTagName("label")
to select all the label element in your page and then use
r[0].innerHTML ="new text"
to select first label and set the text to "next text" in your test() function
I tried to use ideas from the above to get a working example, and had some problems. So I asked for help in another posting and #KrishCdbry very kindly fixed the problem. The posted question is at javascript - How to dynamically change information displayed by radio button? Below is the working example with Krish's changes
<html>
<form name="myform" onsubmit="OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1"
checked> <label for="alsoFirst"> Answer 1 </label>
<input type="radio" id = 'second' name="operation" value="2">
<label for="alsoSecond">Answer 2</label>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementsByTagName('label') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.getElementById('first').checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.getElementById('second').checked == true)
{
alert ( "You have selected the SECOND answer" );
}
return false;
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
With jQuery, $('label[for=male]').html('New Label');
Plain JS:
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
Can also chain that together:
var label = document.getElementById('male').getElementsByTagName('label')[0];
label.innerHTML = 'New Text;

JavaScript event listener quiz

I am fairly new to Javascript and up until this point, have mainly been working through codecademy.com's JavaScript course, which has been great but focuses just on writing JavaScript code and not on using it for web development purposes(i.e. tying it in with HTML and CSS).
I recently got a JavaScript course from Udemy.com which does focus on usuing JavaScript for web development, which has also been great so far but there are some minor things that the instructor does which I know are not considered best practices anymore(the course may be a bit dated).
The main one is he is using HTML event handler attributes as opposed to using event listeners. I am trying to modify the code in the example to use an event listener, but so far I have had no success. I was hoping someone might be able to give a struggling newbie some insight into what I am doing wrong.
The HTML:
<!DOCTYPE html>
<html>
<head>
<title>Simple JavaScript Quiz</title>
<link rel ="stylesheet" href="css/style.css">
<script type = "text/javascript" src="js/script.js"></script>
</head>
<body>
<div id = "container">
<header>
<h1> Simple Javascript Quiz </h1>
<p> Test your knowledge in <strong>JavaScript fundamentals.</strong> </p>
</header>
<section>
<div id = "results"></div>
<form name = "quizForm" id = "qForm">
<h3>1. In which HTML element do we put in JavaScript code?</h3>
<input type = "radio" name = "q1" value = "a" id = "q1a">a. <js><br>
<input type = "radio" name = "q1" value = "b" id = "q1b">b. <script><br>
<input type = "radio" name = "q1" value = "c" id = "q1c">c. <body><br>
<input type = "radio" name = "q1" value = "c" id = "q1d">d. <link><br>
<h3>2. Which HTML attribute is used to reference an external JavaScript file?</h3>
<input type="radio" name="q2" value="a" id="q2a">a. src<br>
<input type="radio" name="q2" value="b" id="q2b">b. rel<br>
<input type="radio" name="q2" value="c" id="q2c">c. type<br>
<input type="radio" name="q2" value="d" id="q2d">d. href<br>
<h3>3. How would you write "Hello" in an alert box?</h3>
<input type="radio" name="q3" value="a" id="q3a">a. msg("Hello");<br>
<input type="radio" name="q3" value="b" id="q3b">b. alertBox("Hello");<br>
<input type="radio" name="q3" value="c" id="q3c">c. document.write("Hello");<br>
<input type="radio" name="q3" value="d" id="q3d">d. alert("Hello");<br>
<h3>4. JavaScript is directly related to the "Java" programming language</h3>
<input type="radio" name="q4" value="a" id="q4a">a. True<br>
<input type="radio" name="q4" value="b" id="q4b">b. False<br>
<h3>5. A variable in JavaScript must start with which special character</h3>
<input type="radio" name="q5" value="a" id="q5a">a. #<br>
<input type="radio" name="q5" value="b" id="q5b">b. $<br>
<input type="radio" name="q5" value="c" id="q5c">c. #<br>
<input type="radio" name="q5" value="d" id="q5d">d. No Special Character<br>
<br><br>
<input type = "submit" value ="Submit Answers">
</form>
</section>
<footer>
<p>Copyright © 2014, All Rights Reserved</p>
</footer>
</div>
</body>
</html>
The JavaScript:
function submitAnswers() {
var total = 5;
var score = 0;
//get user input
var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;
var q4 = document.forms["quizForm"]["q4"].value;
var q5 = document.forms["quizForm"]["q5"].value;
var qArray = [q1, q2, q3, q4, q5];
//reminds user to select each button if left unselected
for (var i = 0; i < qArray.length; i++) {
if (qArray[i] === null || qArray[i] === "") {
alert("You forgot to fill out question " + [i + 1]);
return false;
}
}
//set correct answers
var answers =["b", "a", "d", "b", "d"];
//check answers
for (var i = 0; i < qArray.length; i++) {
if (qArray[i] === answers[i]) {
score++;
}
}
//display results
var results = document.getElementById('results');
results.innerHTML = '<h3>You scored <span>' + score + '</span> out of <span>' + total + '</span></h3>';
return false;
};
var qForm = document.getElementById('qForm');
qForm.addEventListener('submit', submitAnswers, false);
The project is a simple HTML quiz that consists of 5 multiple choice questions.
When the submit button is clicked the code should calculate the score and write the result to an empty <div> element at the top of the page. If any question is left with an unchecked radio button, an alert window should pop up letting the user know.
The code runs fine when I use the HTML event handler attribute, but when I remove the HTML event handler and use the event lister instead I can't seem to get the code to run.
The specific issue here is that your script is referenced in the head element so it starts executing before the DOM is built and your qForm variable is null.
You will want to move the script reference to the bottom of the file. You also should add an event as a parameter to your function and call event.preventDefault() early on, so that your form does not end up submitting inadvertently if the return false is not reached for some reason.
Finally, you are not reading the radio button checked status correctly, but since you are learning I would leave that for you to figure.
Since you are using addEventListener prevent form submission with preventDefault method:
function submitAnswers(e) {
e.preventDefault();
// rest of the code ...
}
In your previous version when you used inline event registration onsubmit="return submitAnswers()" you could use simple return false to do the same.
Demo: http://jsfiddle.net/7xggt9ky/

JavaScript read radio button value in IE and FireFox

I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...
var form = document.forms['myForm'];
var env = form.env.value;
The form itself looks like this...
<form name="myForm" action='JavaScript:xmlhttpPost("/path/to/some/pythoncode.py")'>
<input type="radio" name="env" id="env" value="inside">Inside
<input type="radio" name="env" id="env" value="outside" checked="checked">Outside
<input type="radio" name="env" id="env" value="both">Both
<input type="radio" name="env" id="env" value="neither">Neither
I have some text boxes on the form that I can use the same technique to find the value (
var name = form.fname.value
with a
<input type="text" name="fname" id="fname">
However, when I submit the form and build my post, the value for the radio buttons is always undefined. It works fine in Chrome, but nothing in IE or FireFox.
I tried var env = document.getElementById('env').value, but for some reason that always defaults to the first value (inside) no matter what I select. That method also does not return a value when using Chrome.
Is there something I'm missing for reading the checked value of a radio input in FF or IE?
Try this
function getValueFromRadioButton(name) {
//Get all elements with the name
var buttons = document.getElementsByName(name);
for(var i = 0; i < buttons.length; i++) {
//Check if button is checked
var button = buttons[i];
if(button.checked) {
//Return value
return button.value;
}
}
//No radio button is selected.
return null;
}
IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.
You are using the same ID for multiple Elements, ID is unique for element on the page.
use different IDs.
edit: names can be the same. because then the radio buttons are as a group.
As stated, the IDs should be different to be valid, but you could accomplish this by eliminating the IDs all together and using just the input name:
var form = document.forms['myForm'];
var radios = form.elements["env"];
var env = null;
for(var i=0;i<radios.length;i++) {
if(radios[i].checked == true) {
env = radios[i].value;
}
}
<form name="myForm">
<input type="radio" name="env" value="inside">Inside
<input type="radio" name="env" ivalue="outside" checked="checked">Outside
<input type="radio" name="env" value="both">Both
<input type="radio" name="env" value="neither">Neither
</form>
Short & clear on ES-2015, for use with Babel:
function getValueFromRadioButton( name ){
return [...document.getElementsByName(name)]
.reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}
console.log( getValueFromRadioButton('payment') );
<div>
<input type="radio" name="payment" value="offline">
<input type="radio" name="payment" value="online">
<input type="radio" name="payment" value="part" checked>
<input type="radio" name="payment" value="free">
</div>
You can try this:
var form = document.querySelector('form#myForm');
var env_value = form.querySelector('[name="env"]:checked').value;

Issue with processing form i ajax with radio buttons

I have this script which makes possible the insertion of some data using ajax and php.
Now , all works fine, except the radio buttons (the select options work fine as well) , and it takes the first value of the radio buttons..
Why is this happening?
Here is the code:
<div id="formfields" ><label>Tipologia Pdv: </label>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv" value="Iper" style="width:40px;" /><span > Iper</span>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv"
value="Super" style="width:40px;" /><span > Super</span><br /><br /></div>
<div id="formfields" ><label>Richiesta Ccnl: </label>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl" value="Si" style="width:40px;"/><span> Si</span>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl"
value="No" style="width:40px;"/><span> No</span><br /><br /></div>
The javascript:
// Fetch data from input fields.
var js_tipologia_pdv = $("#tipologia_pdv").val();
var js_richiesta_ccnl = $("#richiesta_ccnl").val();
//let's put all data together
var myData = 'postTipologia_pdv='+ js_tipologia_pdv + '&postRichiesta_ccnl='+ js_richiesta_ccnl + '&postDistretto_pdv=' + js_distretto_pdv + '&postCoopva_pdv=' + js_coopva_pdv + '&postNome_pdv=' + js_nome_pdv;
In php they go something like this:
$postTipologia_pdv = filter_var($_POST["postTipologia_pdv"], FILTER_SANITIZE_STRING);
$postRichiesta_ccnl = filter_var($_POST["postRichiesta_ccnl"], FILTER_SANITIZE_STRING);
Making my comments into an answer:
1) Your id attributes need to be unique.
2) Get the value of the selected radio button using something like: $('input:radio[name=tipologia_pdv]:checked').val();

How can we access the value of a radio button using the DOM?

How can we access the value of a radio button using the DOM?
For eg. we have the radio button as :
<input name="sex" type="radio" value="male">
<input name="sex" type="radio" value="female">
They are inside a form with name form1. When I try
document.getElementByName("sex").value
it returns 'male' always irrespective of the checked value.
Just to "generify" Canavar's very helpful function:
function getRadioValue(theRadioGroup)
{
var elements = document.getElementsByName(theRadioGroup);
for (var i = 0, l = elements.length; i < l; i++)
{
if (elements[i].checked)
{
return elements[i].value;
}
}
}
... which would now be referenced thusly:
getRadioValue('sex');
Strange that something like this isn't already a part of prototype.js.
Surprised no-one has suggested actually using the Selector API:
document.querySelector('input[name=sex]:checked').value
Browser support is good
If you need the selected one, most frameworks support functionality like this:
//jQuery
$("input[name='sex']:checked").val()
You can get your selected radio's value by this method :
<script>
function getRadioValue()
{
for (var i = 0; i < document.getElementsByName('sex').length; i++)
{
if (document.getElementsByName('sex')[i].checked)
{
return document.getElementsByName('sex')[i].value;
}
}
}
</script>
There are a couple of ways.
1. Put an id on each input
<input name="sex" id="sex_male" type="radio" value="male">
<input name="sex" id="sex_female" type="radio" value="female">
Then you can use document.getElementById("sex_male")
2. Use something like PrototypeJS (jQuery works too)
Then you can do something like this:
//This loops over all input elements that have a name of "sex"
$$('input[name="sex"]').each( function(elem) {
//Do something
});
Or even this to get at just the "male" radio button:
$$('input[name="sex"][value="male"]').each(function(elem) {
//Do something
});
An easy way to get started with Prototype is include it from Google by adding this between the <head></head> tags of your page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
If you want the selected one, but don't have a framework handy, you can iterate over the element array looking for whichever one is checked:
for (var i = 0; i < document.form1.sex.length; i++) {
if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
}
var list = document.getElementsByName('sex');
for(var i=0;i<list.length;i++){
if(list[i].type=='radio' && list[i].checked){
alert(list[i].value);
break;
}
}
If you use document.form1.sex, you are returned an array.
document.form1.sex[0] = first radio button
document.form1.sex[1] = second radio button
To check which is checked you need to loop:
whoChecked(document.form1.sex)
function whoChecked(fieldName) {
for(var x=0;x<fieldName.length;x++) {
if(fieldName[x].checked) {
return fieldname[x].value
}
}
document.getElementByName("sex").value
You mean getElementsByName('sex')[0].value? (There's no getElementByName.)
That will of course always pick the first input element with that name — the one whose value is indeed male. You then check to see if it's selected by using the ‘.checked’ property.
For this simple case you can get away with:
var sex= document.getElementsByName("sex")[0].checked? 'male' : 'female';
For the general case you have to loop over each radio input to see which is checked. It would probably be better to get the form object first (putting an id on the form and using document.getElementById is generally better than using the ‘name’-based document.forms collection), and then access form.elements.sex to get the list, in case there are any other elements on the page that have name="sex" attributes (potentially other things than form fields).
function getEleByName(){
if(true==document.getElementsByName('gender')[0].checked){
alert('selected gender is: male');
}
else{
alert('selected gender is: female');
}
}
Loops can achieve the task, as others have shown but it could be simpler than using a loop, which will help performance if desired. Also, it can be portable/modular so it can be used for different radio groups.
Simple Example
function getValue(x) {
alert(x.value);
}
<input name="sex" type="radio" value="male" onChange="getValue(this)" />
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
A more complex example:
function getValue(x){
alert(x.value);
}
<fieldset>
<legend>Sex</legend>
<label>Male:
<input name="sex" type="radio" value="male" onChange="getValue(this)"/>
</label>
<label>Female:
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
</label>
</fieldset>
<fieldset>
<legend>Age Group</legend>
<label>0-13:
<input name="ageGroup" type="radio" value="0-13" onChange="getValue(this)" />
</label>
<label>13-18:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>18-30:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>30+:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
</fieldset>
document.all.sex[0].checked
document.all.set[1].checked

Categories