How to change Label Value using javascript - javascript

I want to change the label value from '0' to 'thanks' in below label, on checkbox click event.
<input type="hidden" name="label206451" value="0" />
<label for="txt206451" class="swatch_text" >Chestnut Leather</label>
<input type="checkbox" name="field206451" class="swatch_check" id="txt206451" value="SELECTED"/>
The Javascript is as below.
var cb = document.getElementById('field206451');
var label = document.getElementById('label206451');
cb.addEventListener('click',function(evt){
if(cb.checked){
label.value='Thanks';
}else{
label.value='0';
}
},false);
But this is not working. Any idea?

very simple
$('#label-ID').text("label value which you want to set");

This will work in Chrome
// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'
But after looking, labels doesn't seem to be widely supported..
You can use querySelector
// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

You're taking name in document.getElementById() Your cb should be txt206451
(ID Attribute) not name attribute.
Or
You can have it by document.getElementsByName()
var cb = document.getElementsByName('field206451')[0]; // First one
OR
var cb = document.getElementById('txt206451');
And for setting values into hidden use document.getElementsByName() like following
var cb = document.getElementById('txt206451');
var label = document.getElementsByName('label206451')[0]; // Get the first one of index
console.log(label);
cb.addEventListener('change', function (evt) { // use change here. not neccessarily
if (this.checked) {
label.value = 'Thanks'
} else {
label.value = '0'
}
}, false);
Demo Fiddle

Try
use an id for hidden field and use id of checkbox in javascript.
and change the ClientIDMode="static" too
<input type="hidden" ClientIDMode="static" id="label1" name="label206451" value="0" />
<script type="text/javascript">
var cb = document.getElementById('txt206451');
var label = document.getElementById('label1');
cb.addEventListener('click',function(evt){
if(cb.checked){
label.value='Thanks'
}else{
label.value='0'
}
},false);
</script>

Based off your code, i created this Fiddle
You need to use
var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];
if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.

hope this help someone else :
use innerHTML for using label object.
document.getElementById('lableObject').innerHTML = res.FullName;

Related

Put value straight into input textbox form?

I'm grabbing a the last transaction value from https://api.bitcoinaverage.com/ticker/global/CAD/ and want to update it into an input textbox, but no matter what I try it won't show up.
here's a fiddle
https://jsfiddle.net/h9w5tj8m/2/
var xbtc = new XMLHttpRequest();
xbtc.open('GET', 'https://api.bitcoinaverage.com/ticker/global/CAD/', true);
xbtc.onreadystatechange = function() {
if (xbtc.readyState == 4) {
var ticker = JSON.parse(xbtc.responseText);
price = ticker.last;
document.getElementById('btc').innerHTML = price;
document.getElementById('cad').innerHTML = price;
}
};
xbtc.send();
updated fiddle
use
document.getElementById('cad').value
instead of
document.getElementById('cad').innerHTML
Simply understand with user interacted element input,select,textarea all are call with value for get the data from the elements.
All Other element's are call with innerHTML for get the data from the element
also refer different between .value and .innerHTML
var xbtc = new XMLHttpRequest();
xbtc.open('GET', 'https://api.bitcoinaverage.com/ticker/global/CAD/', true);
xbtc.onreadystatechange = function() {
if (xbtc.readyState == 4) {
var ticker = JSON.parse(xbtc.responseText);
price = ticker.last;
document.getElementById('btc').innerHTML = price;
document.getElementById('cad').value = price;
}
};
xbtc.send();
There is no input type of "textbox". You need to change it to "text" or use a <textarea></textarea>. You can set the value of text input with .value and a textarea with .innerHTML or .value.
This fiddle works fine: https://jsfiddle.net/h9w5tj8m/4/
using value attribute will place the value u retrieved into a particular textbox having a specific id .For Example :
<input type ="textbox " id="a">
</input>
<script>
document.getElmentById("a").value=x;
</script>
//x is the variable where the retrieved data is stored.
try this
document.getElementById('cad').value = price;

HTML select onChange doesnt work

I am not any kind of proficient in JavaScript.
So I wrote a simple function to use on HTML SELECT, but it doesn't work.
JavaScript:
<script type="text/javascript" language="JavaScript">
function changeFormAction() {
var value = document.getElementById("format");
if (value == "freeText") {
document.getElementById("regularExpression").setAttribute("disabled", false);
}
}
</script>
HTML:
<select id="format" name="customFieldType" onChange='changeFormAction()'>
...
</select>
<input id="regularExpression" type=text size=5 name="format" disabled="true">
Any help will be highly appreciated
value in your code contains the element "format". Usually, to get the value, you just add .value as suffix. But since this a select/dropdown you'll have to do:
var element = document.getElementById("format");
var value = element.options[element.selectedIndex].value;
var text = element.options[element.selectedIndex].text;
Now value and text will contain the different strings like below:
<option value="thisIsTheValue">thisIsTheText</option>
Use either to compare with. I'll use both below to show as an example:
function changeFormAction() {
var element = document.getElementById("format");
var sValue = element.options[element.selectedIndex].value;
var sText = element.options[element.selectedIndex].text;
if (sValue == "freeText" || sText == "freeText") {
document.getElementById("regularExpression").removeAttribute("disabled");
}
}
The issue is something else.. It does hit changeFormAction function on change of customField select list..
var value = document.getElementById("regularExpression");
is wrong usage..
you should use it as
var value = document.getElementById("regularExpression").value
And adding from comments for disabling it also can be
document.getElementById("regularExpression").removeAttribute("disabled");
This wont work because you are trying to fetch text box value using document.getElementById("regularExpression").value;
But on page load you are not having any thing as default value in text box
You might be needed to fetch value of select box.
I think you need something like this:
http://jsfiddle.net/ew5cwnts/2/
function changeFormAction(value) {
if (value == "freeText") {
document.getElementById("regularExpression").removeAttribute("disabled");
}
}
HTML:
<select name="customFieldType" onchange='changeFormAction(this.value)'>

javascript - get value parameter from input text

I want to get the value of a text input. I would like to do this by using id and getElementById :
here HTML code :
<form>
<fieldset>
<legend>Input ordinate :</legend>
<input type="text" id="ordinateId" name="input"/>
<input type="button" id="startbuttonId" value="Start particle"/>
</fieldset>
</form>
and Javascript :
<script type="text/javascript">
var button = document.getElementById("startbuttonId");
var value = document.getElementById("ordinateId").value;
console.log(value);
button.onclick = function() {
console.log(value);
}
</script>
but into the console, nothing appears for value. Where is the problem ?
Thanks
The problem is that you are checking for the input's value before it is set(on document load). Just move the variable declaration within the click function like so:
var button = document.getElementById("startbuttonId");
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
JSFiddle
You need to get the value again when the event fires. Just move your var value
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
With your current script you are assigning value only once, which I am assuming is an empty string. You need to put the assignment inside the function so it gets the current value of the input when it is clicked.
<script type="text/javascript">
var button = document.getElementById("startbuttonId");
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
</script>

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

How to get the selected radio button’s value?

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
var value = $('input:radio[name="radiogroupname"]:checked').val();

Categories