Best way to detect changes when values might not exist anymore? - javascript

I've been trying to detect changes in multiple inputs on a web page.
To do that, I used a query like this:
$(.InputClass).data("InitialValues",$(.InputClass).serialize())
(I'm not in front of my code sadly but it should look like this)
Then later I compared the values in .data with the new values and it worked perfectly fine but for one single thing, a GridGiew.
In that GridView, the user can add or remove rows dynamically (adding or removing data). If I save the initial values in the .data, it will be destroyed with the row and both will be undefined (initial and new values). The input I need to check is hidden and the unique value can be accessed using $(.myNewClass).val() (as I tried to use a different class for this specific hidden input)
I was wondering what woudld be the best solution.
I tried to concatenate all val() from myNewClass using something like
var initialValues = $(.myNewClass).map(Function(x){
return x.val()
})
(Again, I am not in fron of my computer, and I am new to javascript and jquery).
It was not working. Intellisense could not see .map (and it crashed).
If there is no better way, could you help me with the way I record the concatenation of my val() values?
If there is a better way, could you please point me in the right direction?
Thank you very much!

At
var initialValues = $(.myNewClass).map(Function(x){
return x.val()
})
.myNewClass should be a String , within quotes $(".myNewClass") .
F at .map() callback should be lowercase f , to prevent calling native Function .
x at first parameter of .map(x) would be the index of the element or object within the collection of elements or objects - not the element ; try adjusting to .map() callback function parameters to .map(function(index, elem)) to correspond to their values within loop.
x.val() within .map() would return error , as x would be the DOM element <input> , not the jQuery object $(x) ; try utilizing x.value , or el.value to retrieve value of current element within loop
Try opening console , clicking "Run code snippet" twice at stacksnippets below . The alert does not appear to be called at stacksnippets, though the error message displays the contents of items at console
// create `items` object ,
// containing `initialValues` , `currentValues` properties,
// set initially to `undefined` ; set to `Array`
// at `load` , `unload` events
var items = {
"initialValues": undefined,
"currentValues": undefined
};
$(window)
.on({
"load": function() {
// set `items.initialValues` array
items.initialValues = $(".myNewClass").map(function(index, elem) {
return elem.value
}).toArray();
console.log("load", items);
},
"unload": function() {
// set `items.currentValues` array
items.currentValues = $(".myNewClass").map(function(index, elem) {
return elem.value
}).toArray();
console.log("unload", items);
alert(JSON.stringify(items, null, 4));
}
});
$(function() {
setTimeout(function() {
// do stuff
// remove first `.myNewClass` element "row"
$(".myNewClass").first().remove();
// change element at index 3 within `.myNewClass` collection
$(".myNewClass").eq(3).val(123);
}, 1500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="hidden" value="1" class="myNewClass" />
<input type="hidden" value="2" class="myNewClass" />
<input type="hidden" value="3" class="myNewClass" />
<input type="hidden" value="4" class="myNewClass" />
<input type="hidden" value="5" class="myNewClass" />
See .map() , .toArray()

Related

What is the opposite of :checked [duplicate]

I have a list of checkboxes:
<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />
I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:
$("input:unchecked").val();
to get an unchecked checkbox's value, but I got:
Syntax error, unrecognized expression: unchecked.
Can anybody shed a light on this issue?
Thank you!
As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:
$("input:checkbox:not(:checked)")
$("input:checkbox:not(:checked)") Will get you the unchecked boxes.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () {
var a = "";
if (this.name != "chkAll") {
a = this.name + "|off";
}
return a;
}).get().join();
This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.
//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
You can use like this :
$(":checkbox:not(:checked)")
To select by class, you can do this:
$("input.className:checkbox:not(:checked)")
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });

Dynamically update form id values using a loop

I have a form a field called Name and with a field's id as:
'id_Name_set-0' on row 0
'id_Name_set-1' on row 1
etc...
'Name_set-0','Name_set-1' are set automatically when the rows are created.
I'm trying to autofill the Name field with the name entered on row 0.
My first approach was:
$('#id_Name_set-0').on('input',function(e){
$('#id_Name_set-1').val(String($('#id_Name_set-0').val()));
});
$('#id_Name_set-0').on('input',function(e){
$('#id_Name_set-1').val(String($('#id_Name_set-0').val()));
});
$('#id_Name_set-0').on('input',function(e){
$('#id_Name_set-2').val(String($('#id_Name_set-0').val()));
});
This works fine since i hard-coded the values 0,1,2...but i want to dynamically update those values using a loop.
You can filter your inputs using $('input[id^="id_Name_set-"]'), get the total number of them, and then just skip the first (number 0) one in the loop.
var totalDivs = $('input[id^="id_Name_set-"]').length;
for(var i = 1; i < totalDivs; i++)
{
$("#id_Name_set-" + i).val(i);
}
Obviously adapt the above to your needs such as setting all the inputs to the value of the first input. It's only an example of how to achieve it.
Use JQUERY for this, first get all inputs and set each loop on it.
this.id will get the id of which input where use inputs.
$("input").each(function(){
$(this).on("input",function(){
alert(this.id);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input1"/>
<input id="input2"/>
<input id="input3"/>
<input id="input4"/>

How do I retrieve values from checkboxes in JavaScript, using onchange to trigger a function?

I'm a High School student who takes a programming course (JavaScript) at school. We just had a test (which I miserably failed), but we are allowed to try again.
I have a couple of checkboxes. They all have an onchange which triggers a function later. I want to retrieve their values when I click on the checkboxes.
I've browsed around here a bit and seen something called jQuery. I have no idea what that is, so I would highly appreciate to get my help in pure JavaScript.
Okay, here is what I have of code. Note: Some variables and such are in Norwegian. I don't think it should be a problem, since I show the references to all.
My inputs (checkboxes):
<input type="checkbox" class="tur" value="0" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="1" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="2" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="3" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="4" onchange="funcSjekkBoks(this)">
I only need their value to be numbers, since I will use those in reference to an array list I have later.
Here is my function:
var inputTur = document.getElementsByClassName("tur");
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
var resultatListe = [];
if (checkboxEl.checked) {
resultatListe.push(inputTur.value);
console.log(resultatListe);
}
else {
console.log("usant")
}
}
What I would like to happen (if all checkboxes are checked from top to bottom):
resultatListe = [0, 1, 2, 3, 4]
When I uncheck a checkbox, it's value will be removed from the array.
Here is what currently happens:
When I check a checkbox I get [undefined] in my console, when I uncheck a checkbox I get usant (although that is the expected response, I haven't worked with the else part of my if-sentence yet.)
Below code will work for you:
var resultatListe = [];
function funcSjekkBoks(checkboxEl) {
var value = parseInt(checkboxEl.value);
if (checkboxEl.checked) {
resultatListe.push(value);
console.log(resultatListe);
}
else {
console.log("usant");
var indexToRemove = resultatListe.indexOf(value);
resultatListe.splice(indexToRemove,1);
}
}
You need to keep the array resultatListe outside the function other it will be initialized to empty everytime a checkbox is checked/un-checked, triggering the onchange handler. You were getting undefined as you were accessing 'value' property on HTMLCollection object which does not contain that property. Read more about it on MDN
var inputTur = document.getElementsByClassName("tur");
var resultatListe = [];
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
if (checkboxEl.checked) {
resultatListe.push(parseInt(checkboxEl.value));
}
else {
resultatListe = resultatListe.filter(d => d != checkboxEl.value)
}
console.log(resultatListe);
}
There were 2 mistakes in your logic:
1) You need to define resultatListe outside the function so that it won't get initialized to an empty array everytime
2) In you code resultatListe.push(inputTur.value); inputTur is the HTMLCollection of checkboxes whereas you need the single checkbox.
For the else logic, if the value of each checkbox is going to be unique you can use array.prototype.filter method to filter out the value of checkbox from resultatListe

How to access DOM element's attributes and value inside an event handler function in React?

My render function is
<input type="text" id="search" data-id={form.id} value={form.name} placeholder= "Search..." name="id" onKeyUp={this.keyUpFn}"/>
and my keyUpFn function is
keyUpFn(e){
var textInput = document.getElementById('search');
value1 = textInput.getAttribute('data-id')
value2 = e.getAttribute('data-id')
console.log(value1 )
console.log(value2 )
}
Both console value gives error as getAttribute is not defined. How can I solve this in React?
You can get the data from the Event target object. This is how the code would look
keyUpFn(e){
console.log(e.target.getAttribute('data-id'));
console.log(e.target.value);
}
You can actually get the data requested from the event (e) in your function by accessing
event.currentTarget.dataset.paramater;
keyUpFn(e) {
e.currentTarget.dataset.id
}
You can use getElementsByClassName (or id, name etc.), querySelectorAll, focus.
First two returns an array of all valid elements.

Getting value of radio button with Javascript in same HTML page

I'm new on javascript coding.
I'm kinda creating a survey page by myself. I will ask question as a 'True or False' and will get True as a 1 point, false as a 0 point. there will be multiple questions.
I tried to do it by getElementsByName but it didn't worked. my code is like that. can anyone help me please?
<form>
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q1"> false
</form>
<button onclick="myFunction()">try</button>
<script>
function myFunction()
{
var x=document.getElementsByName("question1").value;
window.alert("your score is " +x);
}
</script>
Radio buttons grouped by name behave differently from select element, i.e. the group hasn't a single value. Also getElementsByName() returns a HTMLCollection, which is an array-like object (see Felix Kling's comment).
I'd suggest you to do something like this (after giving an idto the form):
function myFunction () {
var form = document.getElementById('form'), // a reference to the form element
question = form['question1'], // creates a HTMLCollection from elements having attribute name="question1"
n; // loop index
for (n = 0; n < question.length; n++) { // iterates through items in HTMLCollection
if (question[n].checked) { // checks the current item's 'checked' property
alert("your score is " + question[n].value); // found the checked-one
break; // "checked" found, no need to search more
}
}
}
A live demo at jsFiddle.
Bracket notation in question definition is used for future purposes. Just in case you'd have more radio button groups, which could be handled with this same function, you can pass the name of the group to function, and then use that argument within brackets instead of literal value ('question1').

Categories

Resources