Dynamic number of inputs - javascript

I have problem with dynamic number of radio input in array like that
Color:<br>
<label><input type="radio" name="params[54]" value="21">Blue</label>
<label><input type="radio" name="params[54]" value="38">Yellow</label>
Size:<br>
<label><input type="radio" name="params[12]" value="32">S</label>
<label><input type="radio" name="params[12]" value="44">M</label>
<label><input type="radio" name="params[12]" value="58">L</label>
It could not be only Color and Size and it shoud have more than two or three inputs.
I use VueJS Component.
export default {
data () {
return {
params: {}
}
},
methods:{
update: function(){
// here I want use params
}
}
}
I need watch change input and get params object witch one are selected like:
{
54: 21,
12: 44
}
In my old jQuery code I do this like that
$("input[type=radio]").on("change", function(){
var selected = {};
$("input:checked").each(function(a, b){
selected[$(b).data("param-id")] = $(b).data("value-id");
});
});
But in this I seriously don't know how can I do this in Vue. Any ideas?
EDIT:
I sove it by passing list of params
var params = JSON.parse(this.$attrs.params);
for(var key in params){
this.$set(this.params, key, 0);
this.$watch("params."+key, function(){
this.update();
});
}
And adding v-model to input
<label>
<input
:checked="params[54] == 21"
v-model="params[54]"
type="radio"
name="params[54]"
v-bind:value="21"
>
Blue
</label>
Now I can use this.attributes to get object of selected params.

Related

Dynamically loop through checkboxes and get their value and isChecked

I am dynamically printing out checkboxes depending on list from database, called in the code 'coachProperties'. Each coachProperty will get their own checkbox appended with the text which is unique.
I want to add this to another object 'properties'. Something like 'properties{text1 : "false, text2 : "true"} to then later on take it to server-side to do some filtering. I dont want any sumbit button since i want it to dynimcally update which i have js code for. All values in 'properties' will start with "false" which should update when checkbox is clicked. The problem is, sometimes when I uncheck a box it still displays as true and vice versa.
<div data-id="coachPropertiesCheckbox">
<% coachProperties.get('coachProperties').forEach(function (coachProperty) { %>
<div class="checkboxes">
<label>
<input type="checkbox" data-id="test" value="<%= coachProperty.text %>"> <%= coachProperty.text %>
</label>
</label>
</div>
<% }); %>
</div>
Js code:
function setProp(obj,prop,value){
obj[prop] = value;
};
var properties = {};
coachProperties.get('coachProperties').forEach(function (coachProperty) {
properties[coachProperty.text] = "false";
});
view.$el.find('[data-id="coachPropertiesCheckbox"] div.checkboxes input').change(function () {
var isCheckboxedChecked = view.$el.find('[data-id="test"]').is(':checked');
var valueCheckbox = $(this).attr("value");
setProp(properties, valueCheckbox, isCheckboxedChecked );
$.each( properties, function( key, value ) {
console.log( key + ": " + value );
});
});
Use value property to hold data that you would like to associate with the checkbox and do not use it to toggle true and false. Whether checkbox is checked or not, you can know from the checked property.
A piece of advice, most probably, you'll NOT want to use checkbox label same as value because values are for internal purpose, for any data manipulation, and labels have sole purpose of display in the UI.
Please try the following solution direction:
$('.checkboxes input').on('change', (event) => {
const checked = $(event.target).prop('checked')
const value = $(event.target).prop('value')
console.log(checked, ':', value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="checkbox1-id" value="checkbox-1" /><label for="checkbox1-id">Checkbox 1</label>
<input type="checkbox" id="checkbox2-id" value="checkbox-2" /><label for="checkbox2-id">Checkbox 2</label>
<input type="checkbox" id="checkbox3-id" value="checkbox-3" /><label for="checkbox3-id">Checkbox 3</label>
</div>
view.$el.find('div.checkboxes input').change(function (event) {
var id = $(event.target).attr('data-id');
if ($(event.target).prop('checked')) {
resultSetParameters.get('filter').coachProperties.push(id);
resultSetParameters.trigger('change');
} else {
var index = resultSetParameters.get('filter').coachProperties.indexOf(id);
if (index > -1) {
resultSetParameters.get('filter').coachProperties.splice(index, 1);
resultSetParameters.trigger('change');
}
}
});

Complementary State with 2 checkboxes in knockout.js

I have two checkboxes That I would like to have complementary states.
for example: one checkbox is initially selected, so automatically, the other one is unchecked. If I toggle each one of them, the other one toggles too, but with a complementary state.
How can I do this with html and ko.js?
No need any library to do it. You can use it with pure JavaScript as below.
var cb = document.querySelectorAll('input[type=checkbox]');
let toggleCb = function(i){
let index = i ? 0 : 1;
cb[index].checked = !cb[index].checked;
}
for(let i=0; i<=1; i++){
cb[i].onclick = function(){
toggleCb(i);
}
}
<input type="checkbox" id="cb1" checked />
<input type="checkbox" id="cb2" />
Edit:
After seeing your comments, hope I've got this right.
You want the initial values to come from another viewmodel.
Both checkboxes can be unchecked but only 1 can be checked at a time after the initial setting is done. Correct? In this case writable computed observables are no longer required.
var viewmodel1 = function(){
var self = this;
self.initialValueCheckA = false;
self.initialValueCheckB = true;
};
var viewmodel2 = function(data){
var self = this;
self.checkA = ko.observable(data.initialValueCheckA);
self.checkB = ko.observable(data.initialValueCheckB);
self.checkA.subscribe(function(newAValue){
if(newAValue){
self.checkB(false);
}
});
self.checkB.subscribe(function(newBValue){
if(newBValue){
self.checkA(false);
}
});
};
var instance1 = new viewmodel1();
var instance2 = new viewmodel2({
initialValueCheckA: instance1.initialValueCheckA,
initialValueCheckB: instance1.initialValueCheckB
});
ko.applyBindings(instance1, document.getElementById('section1'));
ko.applyBindings(instance2, document.getElementById('section2'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="section1">
A
<input type="checkbox" data-bind="checked: initialValueCheckA" />
B
<input type="checkbox" data-bind="checked: initialValueCheckB" />
</div>
<div id="section2">
A
<input type="checkbox" data-bind="checked: checkA" />
B
<input type="checkbox" data-bind="checked: checkB" />
</div>

Looping through checkboxes with javascript

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
Also in your html end your tag /> i.e.
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
Code
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);
Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].
Replace checkArray[i] with checkArray[i-1] inside the for bucle

input field displaying NaN

Description
Hi, I am using knock out. I have three checkboxes and an input field. When I click on checkbox, the value of the checkbox should appear on the input field. However, instead of getting the value of the checkbox, I see NaN.
jsFiddle link
function ViewModel() {
var self = this;
self.primaryClass = ko.observable("50");
self.secondaryClass = ko.observable("40");
self.otherClass = ko.observable("10");
self.selectedValues = ko.observableArray([]);
self.sum = ko.computed(function () {
var total = 0;
ko.utils.arrayForEach(self.selectedValues(), function (item) {
total += parseInt(item);
});
return total;
});
}
ko.applyBindings(new ViewModel());
Looking at the code, on this line,
total += parseInt(item);
the variable item is the value of your checkboxes.
<input data-bind="checked: selectedValues" type="checkbox" value="primaryClass">500</input>
<input data-bind="checked: selectedValues" type="checkbox" value="secondaryClass">200</input>
<input data-bind="checked: selectedValues" type="checkbox" value="otherClass">100</input>
meaning you are trying to parseInt("primaryClass") ... and so on.
Try changing the value of the checkbox to numbers.
Like here: http://jsfiddle.net/2L4W9/
Check this out:
http://jsfiddle.net/Dtwigs/uFQdq/5/
Do your inputs like this to make them dynamic:
<label>
<input data-bind="checked: selectedValues, value: primaryClass" type="checkbox"></input>
<span data-bind="text: primaryClass"></span>
</label>
Change your values to the values in text.

How to find input type based on it's name Javascript/Mootools

I have a form that submits values to database via Ajax and works fine but I also need to give option to user to reset the form to its default values in case they make a mistake.
The default values are stored in a javascript variable as json object
{"field_name1":"2","field_name3":"3","field_name3":"1000"...
problem I have is that the form has multiple input types , textarea , select , radio
and I need to figure out what they are based on the object key , look for name and return type , so I could do something like if radio set checked checked and so on
I tried
Object.each(dafaultValues, function(value, key){
var filed_name = MyForm.elements[''+key+''];
console.log(filed_name.type);
});
problem with this is that radio type have same name but different id's
<input type="radio" name="field_name5" id="field_name51" value="1">
<input type="radio" name="field_name5" id="field_name52" value="1" checked="checked">
and I endup with js error
Uncaught TypeError: Cannot read property 'type' of undefined
so what would be the best way to find out what the input type is before I can do
if(field.type ='radio'){
//set checked checked..
}
Take a look at this example. I just put it together very dirty, but you will get the idea ;)
HTML:
<form id="test">
<input type="radio" name="abc" value="1"/>
<input type="radio" name="abc" value="2"/>
<input type="radio" name="abc" value="3"/>
<input type="text" name="def" value="change" />
</form>​
JS:
var values = {
'abc': '2',
'def': 'original'
};
var els = $('test').getElements('[name="abc"], input');
els.each(function(el) {
var defaultVal = values[el.get('name')],
type = el.get('type');
if (typeof defaultVal != 'undefined') {
return;
}
if (type == "radio") {
if (el.get('value') == defaultVal) {
el.set('checked', 'checked');
} else {
el.erase('checked');
}
}
if (type == "text") {
el.set('value', defaultVal);
}
});

Categories

Resources