vue js - disable nextTick function - javascript

in my scenario i have differents radio buttons groups, when i check one different radio button, the others will be unchecked.
So i used this function inside a method:
function clearRadioGroup(GroupName){
var ele = document.getElementsByName(GroupName);
for(var i=0;i<ele.length;i++){
ele[i].checked = false;
}
return;
}
apparently it work, but next to this function vue call this one:
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
when vue go inside this handler the other checkboxes have the same behavior than before...
so i want to ask, there is some way to prevent this behavior? thanks in advance

You can easily achieve it with normal HTML template:
<input type="radio" id="one" value="One" v-model="picked">
<label for="one">One</label>
<br>
<input type="radio" id="two" value="Two" v-model="picked">
<label for="two">Two</label>
Remember they should have same v-model value

Related

how to store dynamically created checked checkbox in array?

I am having dynamically created checkbox...
I want that checked value from the checkbox should be stored in one array...
I am Facing the following Problems...
*
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
If I alert the value of checkedvalue It given undefined
If I have console.log the final variable console.log(array); It given the
["on"] in the console.log if the value is checked.
I didn't get the actual value.My code is given below. I don't know what is the mistake I did. Anyone could you please help me.
Thanks in Advance
<input type="Submit" Value="add" onclick="searchinput()">
--------------
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
alert(checkedvalue.value);
for (var i = 0; i < checkedvalue.length; i++) {
array.push(checkedvalue[i].value);
console.log(array);
}
}, false);
}
one of the problems you are facing is that
document.querySelectorAll('input[type=checkbox]:checked');
returns a NodeList and value is not a property on an NodeList object. That is why you are seeing "undefined" in your alert.
Changing as little of your code as possible, I think this should work:
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue = document.querySelectorAll('input[type=checkbox]:checked');
for (var i = 0; i < checkedvalue.length; i++) {
if(checkedvalue[i].checked) {
array.push(checkedvalue[i].value);
}
}
}, false);
}
If you have a form with a bunch of checkboxes and once the form is submitted you want to have the values of all the checkboxes which are checked stored in an array then you can do it like this.
const checkboxes = document.querySelectorAll("input[type=checkbox]");
const form = document.querySelector("form");
const arr = [];
form.addEventListener("submit", (e) => {
e.preventDefault()
checkboxes.forEach(chbox => {
if (chbox.checked) {
arr.push(chbox.value)
}
})
console.log(arr)
})
<form>
<label>Apple:
<input type="checkbox" value="apple" name="test"></label>
<label>Mango:
<input type="checkbox" value="mango" name="test"></label>
<label>Banana:
<input type="checkbox" value="banana" name="test"></label>
<label>Grape:
<input type="checkbox" value="grape" name="test"></label>
<button type="submit">Submit</button>
</form>

Enable button if radio button selected

I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok

How to store add params in api url using angular js

my angular js function code
$scope.cardcall = function (cardtype) {
$scope.cityname=cityname;
$http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(function(data) {
$scope.deal = data.deals;
});
};
my view code
<div class="check_box" ng-repeat="cardtype in card.cardTypes.buckets">
<label>
<input type="checkbox" value=" {{cardtype.key}}" name="cardname" ng-click="cardcall(cardtype)" /> {{cardtype.key}}
</label>
</div>
now when some click on check box it call api like
/api/v1/asasas&filterBy=cardNames&filterByValue=asssas
What i am try to make when some one click 2nd check box then api call like
/api/v1/asasas&filterBy=cardNames&filterByValue=asssas,xsdza
You could add a .checked value to cardtype via ng-model
<input type="checkbox" ng-model="cardtype.checked" value=" {{cardtype.key}}" name="cardname" ng-change="typecall()" />
Then you could run a loop in your code to determine what's checked
$scope.cardcall = function () {
$scope.cityname=cityname;
var keys = [],
buckets = $scope.card.cardTypes.buckets;
for (var i = 0, len = buckets.length, i < len; i++) {
if (buckets[i].checked)
keys.push(buckets[i].key);
}
if (keys.length) {
keys = keys.join();
$http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue=' + keys}).success(function(data) {
$scope.deal = data.deals;
});
}
};
This will be called every time one of those checkboxes gets checked or unchecked and since it looks through all of the checkboxes there's no need to pass cardtype.key anymore. If no checkboxes are checked it won't do an AJAX call.

Get the value of checked checkbox?

So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.

Getting radio-button value on a loop

I am working with a javascript function which takes the value of some questions using RadioButtons of YES or NO. To get the value of one question(Q1) I do something like this:
for (i=0; i<document.form1.Q1.length; i++){
if(document.form1.Q1[i].checked)
Array[0] = document.form1.Q1[i].value;
}
I have to do this for every question, so the code is getting very long. So I am trying to make a function or a loop in which the name of the question is changing. My only problem is that i dont know how to use a Variable on document.form1.VARIABLE.value. I already tried some ways but didnt work.
Can anyone help me with this?
Thanks a lot!
use
document.forms['form-name']['radio-button-name'].value
and give radio button names like que_1 que_2 so you can change that with i using string concatenation
Here's a loop that will traverse your radio buttons and build an array with the values. In the code and example, it's set for testing three questions (named Q1, Q2, and Q3). When done, the array "aux" contains the list of checked values:
var max = 3;
var aux = new Array();
function getCheckedValue(groupName) {
var radios = document.getElementsByName(groupName);
for (i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
return null;
}
function check() {
for(var i=1;i<=max;i++) {
//console.log(i,getCheckedValue('Q'+i));
aux[i-1] = getCheckedValue('Q'+i);
}
console.log(aux);
}
​
jsFiddle example.
Don't use radio buttons, use checkboxes instead (checked=yes, unchecked=no). Then you can iterate your checkboxes freely, and see what's checked and not. Striked out, OP needs the difference between "yes", "no" and "no answer".
After some extensive coding (my JS is rusty) I came up with the following:
<form name=form1 id=form1 action="index.php">
<p>Question 1</p>
<label><input type="radio" name="Q1" value="yes">Yes</label>
<label><input type="radio" name="Q1" value="no">No</label>
<p>Question 2</p>
<label><input type="radio" name="Q2" value="yes">Yes</label>
<label><input type="radio" name="Q2" value="no">No</label>
<p>Question 3</p>
<label><input type="radio" name="Q3" value="yes">Yes</label>
<label><input type="radio" name="Q3" value="no">No</label>
<button id="go">Go!</button>
</form>
<script type="text/javascript">
check = function (e) {
e.preventDefault(); //Don't submit!
var result = [];
var form = document.getElementById("form1");
for (var i = 1; typeof(form["Q" + i]) != "undefined"; i++) {
for (var j = 0; j < form["Q" + i].length; j++) {
if (form["Q" + i][j].checked) {
result.push(form["Q" + i][j].name + " " + form["Q" + i][j].value);
}
}
}
console.log(result);
}
button = document.getElementById("go");
button.onclick = check;
</script>
Triggered by clicking the "Go!" button.
The point is using the string concatenation of "Q" and i to get to "Q1" "Q2" etc.

Categories