Grabbing the value of checkbox in Vue - javascript

Hey so I'm currently a newbie in Vue so have some mercy :)
I am trying to implement a filter bar, where I want to render the checked-box onto a collection view. So a use case would be, if T-shirts was checked then that should render all T-shirts from a DB.
So currently I'm grabbing all the values of beers from my database and rendering that into my filter box:
<div class="overflow menu-list">
<ul>
<li v-for="brewery in breweryName">
<input type="checkbox" name="beer">{{brewery}}
</li>
</ul>
</div>
Where my Vue instance is defined as so:
var filterVM = new Vue({
el: '#filter-bar',
data : {
breweryName : grabFromBeerDB("brewery"),
beerStyle : grabFromBeerDB("style"),
checkedBrewery : []
},
firebase : {
beerList: beerDatabaseRef
}, ...
My only question here is how would I reactively grab the values of the boxes that are checked?
Thanks for the help

Just use v-model
<input type="checkbox" name="beer" value="A" v-model="checkedBrewery">
<input type="checkbox" name="beer" value="B" v-model="checkedBrewery">
<input type="checkbox" name="beer" value="C" v-model="checkedBrewery">
docs: https://v2.vuejs.org/v2/guide/forms.html#Checkbox

<li v-for="brewery in breweryName">
<input type="checkbox" name="beer" :value="brewery" v-model="checkedBrewery">
{{brewery}}
</li>
The value of input is required, and you must make sure each value is different with others.

Related

select default for radio buttons inside a loop modelled with dynamic ngModel

I have a for loop containing inputs, each loop consists of five radio values whose name and model are dynamic.
I want to set value 1 as default, I can use the usual html "checked" or "checked = checked" but it works only without ngModel, if I'm using ngModel, I have to initialize it in the component class but since, it's dynamic there's no way I can initialize it first.
Is there any alternative or am I missing anything??
<div class="scorecard-attribute" *ngFor="let attribute of opportunity.scorecard.scorecard_attributes">
<input type="radio" name="{{attribute.name}}" [value]=1 [(ngModel)]="newRating[attribute.id]" checked>
<input type="radio" name="{{attribute.name}}" [value]=2 [(ngModel)]="newRating[attribute.id]">
<input type="radio" name="{{attribute.name}}" [value]=3 [(ngModel)]="newRating[attribute.id]">
<input type="radio" name="{{attribute.name}}" [value]=4 [(ngModel)]="newRating[attribute.id]">
<input type="radio" name="{{attribute.name}}" [value]=5 [(ngModel)]="newRating[attribute.id]">
You can try this code in your HTML file,
<div class="scorecard-attribute" *ngFor="let attribute of opportunity.scorecard.scorecard_attributes">
<input type="radio" [value]="attribute" [(ngModel)]="newRating" (click)="click(attribute)">{{attribute.name}}
</div>
Add this code in component file,
newRating:any=opportunity.scorecard.scorecard_attributes[0];
click(obj){
console.log(obj);
}
Thanks,

Tick checkbox via javascript console by lable names

I would like to check boxes via javascript.
The thing is I have a task to check more then 300 checkboxes whith specific names.
I can check one box, or check all boxes... but how to check specific boxes?
Here is an example:
<li id="s1" class="city-select">
<input name="rid" id="r1" value="1" type="checkbox">
<label for="r1" id="l1">Paris</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r2" value="2" type="checkbox">
<label for="r2" id="l2">Plovdiv</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
I would like to tick only "Berlin" and "Paris" - here is what I'm using to tick all:
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){el.checked=true});
And here is what am I trying to type:
$("lable:contains('paris, berlin')").prev().find('input').addAttr("checked");
You have wrong selector to target checkboxes. You need to use:
$("label:contains(Paris),label:contains(Berlin)").prev().prop("checked",true);
Working Demo
Update:
var cities = ["Paris","Berlin"];
$("label:contains('" + cities.join("'),label:contains('") + "')").prev().prop("checked",true);
Working Fiddle for update
It looks like your use of prev should be parent or closest.
So you take the current label, go up to the container, then down to the checkbox.
If you use prev then you restrict how much you can change the html (eg if you add a div wrapper around the label in the future, you'll have to change all your code).
given:
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
then use
$("label:contains(Paris),label:contains(Berlin)")
.closest("li")
.find(":checkbox")
.prop("checked",true);
More info at the API documentation: https://api.jquery.com/closest/
How to use this for 300 cities?
This depends on how they are stored. If it's a comma separated list (Paris,Berlin) then split into an array first, if it's json, then convert to an array first...(see the pattern?)
var citiesList = "Paris,Berlin".split(",");
$(citiesList).each(function() {
$("label:contains(" + this + ")")
.closest("li")
.find(":checkbox")
.prop("checked",true);
});

Show a users answers at the end of a quiz

I've created a simple quiz and am storing the users answers in a database. I have access to the answers as json, which looks like this:
{
"form":{
"1":{
"M1_Q1PRE":{
"a1":"a1"
}
},
"2":{
"M1_Q2PRE":{
"a2":"a2"
}
},
"3":{
"M1_Q3PRE":{
"a2":"a2",
"a4":"a4"
}
}
}
}
(question 3 was multi select checkboxes)
I am trying to build a page at the end of the quiz, that will show all the questions, and the chosen answers that the user chose. I want to hard code the final page:
<p>Question One</p>
<ol type="a">
<li>
<label>
<input type="radio" name="M1_Q1PRE" value="a1"> answer a
</label>
</li>
<li>
<label>
<input type="radio" name="M1_Q1PRE" value="a2"> answer b
</label>
</li>
</ol>
<p>Question Two</p>
<ol type="a">
<li>
<label>
<input type="radio" name="M1_Q2PRE" value="a1"> answer a
</label>
</li>
<li>
<label>
<input type="radio" name="M1_Q2PRE" value="a2"> answer b
</label>
</li>
</ol>
<p>Question Three</p>
<ol type="a">
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a1"> answer a
</label>
</li>
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a2"> answer b
</label>
</li>
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a3"> answer c
</label>
</li>
<li>
<label>
<input type="checkbox" name="M1_Q3PRE" value="a4"> answer d
</label>
</li>
</ol>
What I am trying to do is highlight/check the answers that the user chose using the json result. I can't edit the json, as the backend was built for something else and I am trying to repurpose it for this quiz. Does anyone know of a way to parse through the json and use it to automatically populate the users answers?
here is a jsfiddle: http://jsfiddle.net/mtca9kax/
Thanks,
S
EDIT
http://jsfiddle.net/mtca9kax/2/
I've updated my fiddle to include a more accurate json response. There are also questions that have multiple answers (see Q2... lots of T/F). I've got it working, but don't know how to loop over the data.
This is how I would do it:
You have to loop into your json response, and use the values to select the proper answer.
$.each(results.form, function (ind, val) {
$.each(val, function (inde, value) {
$.each(value, function (index, radio) {
//console.log(radio);
$('input[name="'+ inde +'"][value="'+ radio +'"]').prop("checked", true);
});
});
});
FIDDLE.
You should do loop upon JSON object and map key M1_Q1PRE (for example) on the element with same name.
If you don't like clear javascript use jQuery library or same
(jQuery.each -- for loop, jQuery(element).val() -- for set value to the element).
You can iterate over the json/js-object and set the checked property for the users answers:
var answers = JSON.parse(your_json);
for(var i in answers) {
var answer = answers[i];
$('ol:eq(+'parseInt(i)+)' input[value="'+answer['M1_Q'+i+'PRE']+'"]').prop('checked', 'checked');
}
As you see, the json format has room for optimization for this purpose ;-)
Oh, there are actually the answers ids as key and values inside the M1_Q... objects - that needs to be solved to make the answer above work... the general idea should be visible, however.
(Better change the json to a more appropriate format.)

finding value of closest hidden field, located above user click in javascript

I'm trying to grab the value of a hidden field that resides above each group of LI's with javascript, I cannot use jQuery because of an unreasonable client's concerns (believe me, I've tried, they just don't want to "risk" adding a library)... anyway...
The list would look something like this:
<input id="hidden1" type="hidden" value="5" class="includeds">
<h3>header</h3>
<ul class="groups">
<li><input id="li1" type="checkbox" value="1" onclick="value()"></li>
<li><input id="li2" type="checkbox" value="2" onclick="value()"></li>
<li><input id="li3" type="checkbox" value="3" onclick="value()"></li>
</ul>
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value()"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value()"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value()"></li>
</ul>
So if I click on checkbox li1, I want to retrieve the value "5" from the hidden field above it.
If I click li5, I want to get the value of "2" from the first hidden field above it, etc, etc.
in a previous SO question some amazing people helped me do this with jQuery:
if($(this).closest('ul').prevAll('.includeds:first').val() !== '0') {
// logic here
}
but when presented to the client, I ran into the aforementioned complaints. So now I need to do the same thing with javascript vanilla. I appreciate any help or pointers you guys could provide. I apologize for asking the same question twice, between jquery and javascript.
Uhm, the jQuery code I'd use would be:
$(this).parent().prev().prev().val()
With that in mind, all you have to do is rewrite the code to correct plain javascript entities.
The result would be something like:
function getParent(node){
return node.parentNode;
}
function getPrev(node){
do { // loop to find the previous node that is an element
node = node.previousSibling;
}while(node && node.nodeType != 1);
return node;
}
getPrev(getPrev(getParent(this))));
If you can't use jQuery then complex queries like the on you mentioned become much more difficult. In liue of jQuery it's easiest to reference elements by their ID tag or by a class filter (depending on the scenario).
Here i would say the best bet is to hard code the given input ID into the onclick function.
HTML
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value('hidden2')"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value('hidden2')"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value('hidden2')"></li>
</ul>
JavaScript
function value(id) {
var elem = document.getElementByID(id);
...
}

jQuery Validation Plugin Multiple Checkboxes

I am having some difficulty in using the jQuery Validator plugin. I have a list of checkboxes with different name attributes and I can't seem to figure out how to ensure that at least one of them has been checked. Everything that I find on Google seems to only work when the name attribute is the same.
Here is some sample code (updated):
<ul id="email_lists">
<li>
<input name="checkbox1" type="checkbox" /> List 1
</li>
<li>
<input name="checkbox2" type="checkbox" /> List 2
</li>
<li>
<input name="checkbox3" type="checkbox" /> List 3
</li>
<li>
<input name="checkbox4" type="checkbox" /> List 4
</li>
</ul>
I want to make sure that at least one of those is checked. Unfortunately, I cannot make the names the same as it is form that submits to a third-party email marketing application and it is expecting specific name attributes for these checkboxes.
Update
I am aware of how to do this using plain jQuery, but I would prefer to use the jQuery Validator plugin since that is how all of the other validation on the page is done.
I can group those checkboxes using jQuery by saying $('#email_lists li');, but I'm not really sure how to use something like that and tell the jQuery Validator plugin to use that as a group.
Assuming that you can give the checkboxes a class name (the jQuery needs something to work with):
<input class="validationGroupOne" name="checkbox1" type="checkbox" />
<input class="validationGroupOne" name="checkbox2" type="checkbox" />
<input class="validationGroupOne" name="checkbox3" type="checkbox" />
<input class="validationGroupOne" name="checkbox4" type="checkbox" />
You should be able to plug in the .validationGroupOne class-selector in place of the, usual, name attribute.
This was my solution :-)
Use:
<div id="list">
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
</div>
<input type="hidden" name="the_real_field_name" />
Then in jquery validate plugin block:
rules : {
chkbox: "required"
},
Then store the values as an array into a single hidden field like:
function updateInput() {
var allVals = [];
$('#list :checked').each(function() {
allVals.push($(this).val());
});
$('#the_real_field_name').val(allVals);
}
$(function() {
$('#list input').click(updateInput);
updateInput();
});

Categories

Resources