add dynamic click on checkbox and to get inputName in jQuery - javascript

I have a dynamic input which will have checkbox to hide the inputs when you tick the checkbox, at the moment I'm trying to add click="getChk() to the checkbox however it was only giving me the last index inputName.
Say I have input Ids (code, sku, id).
My dynamic inputs and checks code line is
for (var x = 0; x < searchParams.length; x++) {
var container = $('#checkBox');
var inputs = container.find('input');
var id = inputs.length + 1;
var inputName = searchParams[x].name;
$('<textarea />', { id: inputName, name: inputName, placeholder: inputName, rows: "2", class: "search-area-txt col-sm-12" }).appendTo(searchbox);
$('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox);
$('<label />', { 'for': 'x' + id, text: inputName, id: inputName, name: inputName }).appendTo(checkBox);
}
But this will need to be saved in the localStorage so when refresh it will persist the input to be hidden when its exists in the localStorage.
Edit: the code below should save the name in the localStorage in array form.
var inputNames = [];
getChk(id){
var indexOfItem = inputNames.indexOf(name)
if (indexOfItem >= 0) {
inputNames.splice(indexOfItem, 1);
} else {
inputNames.push(name);
}
localStorage.setItem('chked', JSON.stringify(inputNames))
}
My attempt is by adding .click(function(){})
$('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox).click(function(){
getChk(id); // only gives me the id name
});
HTML inputs and checkbox html

The issue is because when the click event handler runs the for loop has completed, therefore the id variable holds the last value.
To fix this, amend your click handler to read the id attribute directly from the element which raised the event:
$('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox).click(function() {
getChk(this.id);
});
Also, as spotted by #guest271314, the correct method when setting localStorage data is setItem(), not set():
localStorage.setItem('checked', id);

you can try below code
getChk(e){
localStorage.set('checked', this.id);
console.log('input id>> ', this.id);
}
.click(getChk);

Related

how to keep all the desired input values while changing the inputs to buttons?

When the array is correct it should turn the input fields to btn btn-success buttons (works). Now comes the part I cannot seem to get past: They don't keep their value inserted into the input field. Example: You insert the word "hello" in an input field (and we assume the word "hello" is correct) and it then turns to a green button. However it does not keep it's value. How can I achieve this, but with multiple input fields?
The code looks like this:
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn());
S.addRight();
S.playRight();
}
I tried appending to the button cValue, but that didn't work (as expected).
The function that creates the success button:
function getCorrectBtn() {
var correctBtn = $('<button/>', {
'class': 'btn btn-success buttonCorrect',
'type': 'button',
'id': "button" + CBC++
});
return correctBtn;
}
Here is the complete loop (how the input fields are created aswell):
$.map(exercise.syllables, function (syllable, j) {
if (!syllable || !syllable.trim().length) {
// If it doesn't exist or is an empty string, return early without creating/appending elements
return;
}
var innerSylCol = $('<div/>', {
class: 'col-md-3 inputSyllables'
});
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn());
S.addRight();
S.playRight();
}
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn(cValue));
function getCorrectBtn(value) {
var correctBtn = $('<button/>', {
'class': 'btn btn-success buttonCorrect',
'type': 'button',
'id': "button" + CBC++,
'value': value
});
return correctBtn;
}
This possibly should work.
Understand how replaceWith works. You aren't simply altering the existing input, you are replacing it. Since the value is data for the input, when you replace it, you are wiping out the data. So you must pass the data into the getCorrectBtn function and assign it to the new button.

jquery get first text element attribute from selected dropdown

both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.
$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname + ' ' + value.name +'</option>');
what i would achieve is:
var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe
so, in other hand, i would like get only first element of text in selected dropbox.
I can help me to understand how to reach my goal?
In jQuery, you don't use the .text() method to get the value of a dropdown menu. You need to just have:
var testd = $("#dropDocente").val();
and that will return the selected option's value from the dropdown.
you can add value.surname as a data-surname data tag onto the option and then retrieve that value by selecting the option and using .data('surname'). you can do this for any other value you want to single out as well
$(document).ready(function() {
var values = [
{ surname: "Doe", name: "John", idDocente: "some value here" },
{ surname: "Shmo", name: "John", idDocente: "some value here2" },
{ surname: "Little", name: "John", idDocente: "some value here3" },
];
for (var i = 0; i < values.length; i++) {
var value = values[i];
$('#dropDocente').append('<option value="'+value.idDocente+
'" data-surname="'+ value.surname +'">' + value.surname + ' '
+ value.name +'</option>');
}
// default first
$('.results').text($("#dropDocente option:first").data('surname') + ', ' + $("#dropDocente option:first").val());
// on change, get the surname
$('#dropDocente').on('change', function() {
$('.results').text($("#dropDocente option:selected").data('surname')+ ', ' + $("#dropDocente option:selected").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDocente">
</select>
<br/><br/><br/>
<div class="results">
</div>
You could just split full name on select change.
Something like this:
$('select').on('change', function(){
var id = $(this).val();
var fullName = $('select option:selected').text();
var surname = fullName.split(" ", 1);
});
Full example here: https://jsfiddle.net/1aj06Lw6/1/

Grab dynamic input value in react

This is my form view:
and this is my dynamic input form code:
...
let subJudulInput = []; // this variable will render
for (var i = 0; i < this.props.subtitleInput.index; i++) {
let index = i + 1;
subJudulInput.push(
<div key={'formgroup' + index} class="form-group">
{(i === 0) ? <label for="subJudulInput">Sub Judul</label>:false}
<input key={'input' + index} type="text" class="form-control" placeholder={`Masukan Sub Judul ${index}`}/>
</div>
);
}
...
If I click the plus button, the new input form will show:
This is my form handler:
onAddingTitle(event) { // if the submit button get pressed
let formData = {subJudul:[]};
event.preventDefault();
console.log(event.target.elements);
}
How I can grab all of that dynamic input value? (Best ways) to formData object; like this:
let formData = {subJudul:[
'sub judul 1 value here',
'sub judul 2 value here',
'sub judul 3 value here',
'next new input'
]};
Add name attribute to the text field: name={"textbox-"+index}
Try the below code to get your expected values
onAddingTitle(event) {
event.preventDefault();
let formElements = event.target.elements;
let formData = {
subJudul: []
};
Object.keys(formElements).forEach((key) => {
if (formElements[key].type == 'text') {
formData.subJudul.push(formElements[key].value)
}
});
console.log('formData', formData);
}
Explanation:
Get the form elements (which is a object)
loop through the object elemets using keys
Check the type of the field, if its a textbox(add as per your need) push the value of the field to array.

How do I get a input value on ExtJS 6.0

I wonder how do I get the input value from the form in ExtJS.
I have tried several ways "see comments", but none of them gave me a value, i get an error mostly - "undefined".
Another thing that is unclear is where is form name defined ?
Here's my code:
Ext.onReady(function() {
Ext.create('Ext.form.Panel', {
renderTo: document.body,
title: 'Convert Roman characters to Arabic',
height: 150,
width: 300,
bodyPadding: 10,
defaultType: 'textfield',
items: [
{
fieldLabel: 'Enter Roman Character',
name: 'char'
}
],
buttons: [
{
text: 'Submit',
handler: function() {
//var form = formPanel.getForm();
//var value = form.findField('char');
//var form = this.up('form'); // get the form panel
//var value = Ext.getCmp('char').getValue();
// var field = Ext.getCmp('char');
Ext.Msg.alert('Success', "value");
}
}
]
});
});
In the end the application should alert the inputed value.
Thanks in Advance.
text: 'Submit',
handler: function(btn) {
Ext.Msg.alert('Success',btn.up('form').down('[name=char]').getValue());
//var form = formPanel.getForm();
//var value = form.findField('char');
//var form = this.up('form'); // get the form panel
//var value = Ext.getCmp('char').getValue();
// var field = Ext.getCmp('char');
There are multi ways to get value of char field.
1) To get value like this as you used, you have to give id property for this field :
{
fieldLabel: 'Enter Roman Character',
name: 'char',
id : 'char' // or give any name
}
now used below code to get value
var field = Ext.getCmp('char');
var value = field.getValue();
2) You can also use itemId property same :
{
fieldLabel: 'Enter Roman Character',
name: 'char',
itemId : 'char' // or give any name
}
now used below code to get value
var field = Ext.ComponentQuery.query('#char')[0];
var value = field.getValue();
3) another way, you can get value from form values;
var form = this.up('form'),
formValues = form.getForm().getValues();
charValue = formValues.char;

Passing variable name as id

I am appending the checkboxes in a particular class using some function.. I have a function to run everytime the checkbox is selected.. So I need to get the name and id of the Checkboxes..
Heres the part of the code where I am appending the checkbox dynamically.. Here value is the one I want the id and name attribute to be..
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' onclick='selectMainBrand(\"" + value + "\");' />" + value + "</label>");
});
set the id using
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append('<label class="checkbox"><input type="checkbox" id="' + value + '" onclick="selectMainBrand("' + value + '");" />' + value + '</label>');
});
function selectMainBrand(ids) {
$('#Brands').on("change", "input", function () {
console.log("called");
var selected = this.name;
console.log(selected);
});
}
I'm assuming your UL tag has id="brands". If not change the above code as follows
$('.fpblocks').on("change", "input", function () {
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' id ='someID' name ='someName' />" + value + "</label>");
});
and on checkbox click..
$(".fpblocks .fpblocksBrands_inner ul :checkbox").live('click', function(){
var id = $(this).attr('id'); //get id of checked checkbox
var name = $(this).attr('name'); //get name of checked checkbox
})
remove onclick='selectMainBrand(value);' from inputs' generation code
After checkboxes are generated, you can select name and
$('#Brands input').on("change", function () {
var name=$(this).attr("name");
var id=$(this).attr("id");
alert(name);
alert(id);
console.log(selected);
});
see the DEMO http://jsfiddle.net/BbtEG/
Your dynamically created html (<input type='checkbox' onclick='selectMainBrand(value);' />) does not have a name, or an id. You cannot pass what doesn't exist. To solve this, generate a name and an id to use.
Also in your selectMainBrand function you don't appear to be using the ids parameter that you're passing in. All that function is doing is binding a handler to the input which, since you're using on to bind it, seems silly.
Why not use on to delegate the handler instead? If you delegate the handler, you can grab the name or id from within the handler thereby obviating the need to pass those in as parameters (working demo).
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
//delegate the change handler
$('.fpblocks .fpblocksBrands_inner').on("change", '#Brands input', function (e) {
var selectedName = this.name,
selectedId = this.id,
isChecked = this.checked;
console.log(JSON.stringify({
"called": true,
"selectedName": selectedName,
"selectedId": selectedId,
"isChecked": isChecked
}));
});
If you truly have your heart set on passing in the parameters, there are ways to do that, such as binding the handler within the loop where you create the inputs (working demo):
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
}).click(function (e) {
var self = $(this), // capture the input as a jQuery object (typically very useful)
actualHandler = function (id, name) {
// do stuff
console.log(JSON.stringify({
"called": "actualHandler",
"selectedName": id,
"selectedId": name,
"isChecked": self.prop('checked')
}));
};
actualHandler(this.id, this.name);
// or
actualHandler(self.attr('id'), self.attr('name'));
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
or you could set the onchange attribute in the loop where you create the inputs (working demo):
window.inputHandler = function (id, name) { // must be added to the global scope, otherwise it won't be visible.
// do stuff
console.log(JSON.stringify({
"called": "inputHandler",
"selectedName": id,
"selectedId": name
}));
};
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key, //set the id, appending the key to make it unique
"onchange": "inputHandler('" + "mainBrand" + key + "', '" + "mainBrand" + key + "')"
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
and there are other ways to go about it.
Personally, I would use the delegation.

Categories