I have two radio buttons:
<input type="radio" name="editList" id="prov" value="Admin">Admin
<input type="radio" name="editList" id="user" value="User">User
I want to change values with javascript, and I try as:
var typeu= $('input[type=radio][name=editList]').val();
if (typeu=== "Admin") {
typeu= typeu.val() === "A";
} else if (typeu === 'User') {
typeu= typeu.val() === "U";
But I get issue:
Uncaught TypeError: typeu.val is not a function
Can someone help me please?
Try this
var typeu = $('input[type=radio][name=editList]');
$.each(typeu, function(i, v) {
if ($(v).val() === "Admin") {
$(v).val("A");
} else if ($(v).val() === 'User') {
$(v).val("U");
}
});
https://jsfiddle.net/za61z3vx/
First line, you get all the inputs that match type=radio and name=editList. Since there's more than one it'll be an array, so you need iterate through it.
To check radio button by javascript you should use "prop" function
$('#prov').prop('checked', true );
// or $('#prov').prop('checked', false );
To GET checked prop u should use:
$('#prov').prop('checked');
From your code:
var typeu= $('input[type=radio][name=editList]');
typeu.each( radio => {
const $rb = $(radio);
console.log( $rb.val(), $rb.prop('checked') )
});
Use val(function)
var radioValues = {
'Admin':'A',
'User':'U'
};
$('#prov, #user').val(function(_, existingValue){
// if current value matches keys in object, will return new value
// if not a match will return existing value
return radioValues[this.value] || existingValue;
})
// log updated values for this demo
.each(function(){
console.log(this.id, 'value is', this.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="editList" id="prov" value="Admin">Admin
<input type="radio" name="editList" id="user" value="User">User
Note that your attempt will only return value of the first element. You need to loop over them and deal with each instance
Related
This question already has answers here:
Getting multiple values from checked checkboxes Javascript
(3 answers)
Closed 3 months ago.
I am trying to display multiple checkbox values in a separate DIV to show the results of the checkboxes to the user. But I also want to remove the value if the user de-selects the checkbox. This is the code I have so far but can only display/hide one value at a time. For example, if I click checkboxes a, b, and c, it will show all values. But If I uncheck, they will hide. Thanks
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="a"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="b"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="c"/>
<div id="acc"></div>
function selectAcc(cb) {
var x = cb.checked ? cb.value : '';
document.getElementById("acc").innerHTML = x;
}
// selecting input type checkboxes
const inputCheckBoxes = document.querySelectorAll("input[type=checkbox]");
const main = document.querySelector("#main");
// function to print in main div
const printCheckedValue = (array) => {
main.innerText = "";
array.forEach(value => {
main.innerText += value;
})
}
// to store checkboxed values
let checkedValue = [];
// looping through all inputcheckboxes and attching onchange event
Object.values(inputCheckBoxes).forEach((inputCheckBoxe, index) => {
inputCheckBoxe.onchange = (e) => {
// checking if value is checkedbox or not
if (checkedValue.includes(e.target.value)) {
// if checkeboxed than filtering array
checkedValue = checkedValue.filter(val => val != e.target.value)
printCheckedValue(checkedValue);
} else {
checkedValue.push(e.target.value);
printCheckedValue(checkedValue);
}
}
})
<input type="checkbox" name="accessory" value="a" />
<input type="checkbox" name="accessory" value="b" />
<input type="checkbox" name="accessory" value="c" />
<div id="main"></div>
Hope this works for you .
function selectAcc(cb) {
// get previous div value
var previousValue = document.getElementById("acc").getAttribute('value');
var newValue = previousValue;
//store the new clicked value
var value = cb.value;
// if the new value is checked and the value is not present in the div add it to the div string value
if (cb.checked && !previousValue.includes(value)) newValue+=value ;
// else remove the value from div string value
else previousValue = newValue.replace(value, '');
// update new value in div
document.getElementById("acc").innerHTML = newValue;
}
Try put like something this
var checked = []
function selectAcc(cb) {
if(cb.checked){
checked.push(cb.value)
} else {
var index = checked.indexOf(cb.value)
checked.splice(index, 1)
}
document.getElementById("acc").innerHTML = checked.join(' ');
}
Good day everyone,
I'm trying to make a javascript code to scan through all the input in my form like so:
<form>
<input class="formInputOne" />
<input class="formInputOne" />
<input class="formInputOne" />
<input class="button" type="submit" />
</form>
Now I want my javascript code to scan through all of them and know if they are empty or not like so:
button.addEventListener("click", function () {
let formInputOne = document.querySelectorAll(".formInputOne").value;
if (formInputOne.forEach == "") {
console.log("All fields are required!");
} else {
console.log("Yay! All fields got values");
}
});
I'm really curious to find out a way to loop through all the inputs and know if they contain values.
Please I'm using javascript, but if it can be done with jquery, no probs.
Thanks.
Select inputs, loop through it, get value and log based on value
let inputs = $('.formInputOne').toArray(); //document.querySelectorAll('.formInputOne')
inputs.forEach(e => {
let value = e.value.trim();
if (value == "") {
console.log("All fields are required!");
} else {
console.log("Yay! All fields got values");
}
});
//Check if atleast one value is empty
let bool = inputs.map(a => a.value.trim()).some(a => a == "");
console.log('Empty value is present', bool);
Hi have a html code like this
<input type="text" value="quantita" id="quantita" name="quantita">
<input type="text" value="prodotto" id="prodotto" name="prodotto">
<input type="text" value="prezzo" id="prezzo" name="prezzo">
Now I'm trying to do a jquery code that add a button if the value of all these id is different from NULL
so I do this
var list = $("#prezzo", "#quantita", "#prodotto").val();
if (list!="")
{...do this...}
else
{....do nothing...}
but it doesn't work
You could do it like this instead
var list = $("#prezzo, #quantita, #prodotto").filter(function() {
return this.value === "";
}).length === 0;
if (list) { // All values set
assuming you meant the value is an empty string, as in no value set, and not actually the string NULL ?
$("#prezzo,#quantita,#prodotto").each(function()
{
if ($(this).val() !="" )
{}
else
{}
});
Iam trying check if the text of label matches with the text box if matches then make that specific label text to yes else no but in my code am not sure what is wrong but that is not happening for all it is showing "no" it self
Demo
HTML
<input class="master" value="1">
<label class="user_label" >1</label>
<label class="user_label" >0</label>
<label class="user_label" >1</label>
JS:
$(function() {
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.text === master ? "yes" : "noo";//if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
this.text will be undefined inside fn, because this is a DOM node, and it doesn't have text property.
You can wrap it as a jQuery object and use the text() method:
var fn = function() {
return $(this).text() === master ? "yes" : "noo";
}
http://jsfiddle.net/L6d39f10/5/
You can simplify your code as follows, second parameter in text() callback function refers the old text value. You can use val() for getting value in jQuery.
var val = $('input.master').val();
$('.user_label').text(function(i, text){
return val === text ? 'yes' : 'no';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="master" value="1">
<label class="user_label">1</label>
<label class="user_label">0</label>
<label class="user_label">1</label>
when fn passed into $('label.user_label').text(fn) the context changed but still this.text is undefined. use this.textContent,this.innerHTML,$(this).text()
use text to compare and then modify it that makes logic odd, should it be like this?
$(function() {
$('input.master').keyup(function() {
var master = $(this).val(); // get the master value
var fn = function() {
return $(this).attr('data-val') === master ? "yes" : "noo"; //if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="master" value="">
<label class="user_label" data-val="1"></label>
<label class="user_label" data-val="0"></label>
<label class="user_label" data-val="1"></label>
$(function() {
var master = $('input.master').get(0).value; // get the master value
$('label.user_label').each(function(){
if($(this).text() === master){
$(this).text("yes");
}else{
$(this).text("no");
}
});
});
I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.