can we use and operator to combine multiple jQuery events - javascript

I want to use jQuery to see if three text boxes are changed so I can send data through AJAX.
I tried a simple script:
$("#name, #position, #salary").change(function()
{
console.log("All data are changed");
});
Where name, position and salary are the respective IDs of three text box.
The result was that when I change the first one:
And when I changed the second:
And here is the third one:
So, I've got the message when separately each text box is changed. What I do need is when the three are changed, display the message. I am new to jQuery, so I want to know if I can use something like IF ... AND ... AND in jQuery.

A lot of validation frameworks have the concept of a dirty input once a user has changed the value. You could implement this and check when all your fields are dirty.
$("#name, #position, #salary").change(function() {
this.classList.add("dirty");
if ($(".dirty").length === 3) {
console.log("All data are changed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
We can abstract this out into a jQuery plugin for re-usability
$.fn.allChange = function(callback) {
var $elements = this;
$elements.change(function() {
this.classList.add("dirty");
if (callback && $elements.filter(".dirty").length === $elements.length) {
callback.call($elements);
}
});
return $elements;
}
$("#name, #position, #salary").allChange(function() {
console.log("All data are changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />

You can store changed inputs in an array, and check it's length to detect if all of them where changed.
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
changedInputs.push(this.id);
if(changedInputs.length === 3) {
alert('All 3 inputs where changed!');
}
});

You can try:
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
if !(changedInputs.include(this.id) ){
changedInputs.push(this.id);
if(changedInputs.length == 3) {
alert('All 3 inputs where changed!');
}
});

You can also use this approach. Fiddle
var isNameChanged, isPositionChanged, isSalaryChanged = false;
function fieldsChanged()
{
var id = $(this).attr('id');
if (id == 'name') isNameChanged = true;
else if (id == 'position') isPositionChanged = true;
else if (id == 'salary') isSalaryChanged = true;
if (isNameChanged && isPositionChanged && isSalaryChanged) {
console.log('All have been changed');
isNameChanged = isPositionChanged = isSalaryChanged = false;
}
}
$(function(){
$('#name, #position, #salary').change(fieldsChanged);
});

Try using a class:
<input class="need">
<input class="need">
<input class="need">
$(".need").change(function()
{
var all = 0;
$(".need").each(function(i,v){
if ($(v).val().length >0 ) {
all+=1;
}
});
if(all.length == 3) {
alert('All 3 inputs where changed!');
}
});

Store the multiple selectors in a variable. On .change() loop through the elements in the multiple selector to test the input values. If all inputs have content an additional function can be called.
$(document).ready(function(){
var $selectors = $('#input1, #input2, #input3');
$selectors.change(function(){
var allChanged = true;
console.log($(this).attr('id') + ' was changed.');
$selectors.each(function(){
if ($(this).val() == '') {
allChanged = false;
}
});
if (allChanged) {
// $().ajax();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input id="input3">

one possible solution:
var needed = ["name", "position", "salary"];
$("#name, #position, #salary").change(function()
{
if(needed.length == 0) return;
needed.splice(needed.indexOf($(this).attr('id')), 1);
if(needed.length == 0)
console.log("All data are changed");
});
first, you need to init the array "needed" to all required fields
then, when a field is changed, you remove that field from the needed array
once the array is empty, all required values are changed ;)
the first condition is to ensure not to log the message more than once

You can compare current input value to default one, then the logic could be like following:
btw, i set a common class for all inputs to check, because this is how it should be done imho...
$('.inputToCheck').on('change', function() {
var allInputsChanged = !$('.inputToCheck').filter(function() {
return this.value === this.defaultValue;
}).length;
if (allInputsChanged) alert('All inputs changed!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="name" class="inputToCheck">
<input id="position" class="inputToCheck">
<input id="salary" class="inputToCheck">

Related

how to check hidden input is empty or not use else if conditions in laravel

this is my hidden input field
<input type="hidden" id="hdnship" name="origin_port" value="">
this is my function to get value hidden input field
function myfunction(){
$('#printarray').on('click', function() {
var array = [];
$("input:checkbox[name=origin_port]:checked").each(function() {
array.push($(this).val());
});
alert(array);
$('#hdnship').val(array);
});
}
You can check you input if it is not empty this way:
if( !$("input").val() ) {
console.log("Empty");
}
or
if( $("input").val().length === 0 ) {
console.log("Empty");
}
or If you're sure it will always operate on a textfield element then you can just use 'this.value':
if( !$("input").value ) {
console.log("Empty");
}
I think you should be checking each input type text instead of checked attribute of a checkbox which is basically not the type of your hidden input:
function myfunction(){
$('#printarray').on('click', function() {
var array = [];
$("input[type=text]").each(function() {
if($(this).val().length !== 0) {
array.push($(this).val());
}
});
alert(array);
$('#hdnship').val(array);
});
}
You can try this also for check hidden empty or not
$(document).ready(function(){
$(".jsButton").click(function(){
var array = [],emptyvalue=[];
$("input[type=hidden]").each(function()
{
if($(this).val().length !== 0)
{
array.push($(this).val());
}
else
{
emptyvalue.push("value");
}
});
$('#lblHasValue').html(array.join(','));
$('#lblNotValue').html(emptyvalue.join(','));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="hidden1">
<input type="hidden" value="hidden2">
<input type="hidden" value="hidden3">
<input type="hidden">
<input type="hidden">
<button type="button" class="jsButton">Set & Get Hidden Value</button> <br/>
<lable id="lblHasValue"></lable> <br/>
<lable id="lblNotValue"></lable>
You can set if hidden field has no value if hidden field has value
you get and set

Temporarily disable an input field if second input field is filled

I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">

How can I apply CSS to a link if at least one input is not original, and undo that change if all inputs are original?

I have a bunch of checkboxes, radio buttons, and text fields on my page. They all have '_boom' appended to the end of the id. I want to detect if any one of these inputs is not its original value, and if so, apply CSS to a button called 'save' on the page. Then, if the user reverts any changes they made and all inputs have their original values, I want to undo the CSS.
I've gotten close with the code below. But let's say I check 3 checkboxes. Upon checking the 1st box, the CSS changes. Good! I check the 2nd and 3rd boxes. The CSS stays the same. Good! But then I uncheck ONE of the boxes, and the CSS reverts. Bad! The CSS should only revert if I undo every change.
$('[id*="_boom"]').change(function() {
var sType = $(this).prop('type'); //get the type of attribute we're dealing with
if( sType === "checkbox" || sType === "radio" ){ //checkbox or radio type
var originalCheckedState = $(this).prop("defaultChecked");
var currentCheckedState = $(this).prop("checked");
if(currentCheckedState !== originalCheckedState){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
if( sType === "text" ){ //text type
var originalValue = $(this).prop("defaultValue");
var currentValue = $(this).val();
if(currentValue !== originalValue){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
});
#save {
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
There are many possible improvements in your code to make it cleaner and standardized. Things like instead of relying on id you should consider class attribute and all... but I will not revamp your code. Here's the solution to your existing code.
The idea is loop through all the form elements and if atleast one of the elements is different than its default value then set the flag and come out of the loop.
At the end, check for that flag and set the css accordingly.
For this, I have enclosed your elements into a form form1.
$("#form1 :input").change(function() {
var changed = false;
formElems = $("#form1 :input");
for(i=0;i<formElems.length; i++){
var sType = $(formElems[i]).prop("type");
if(sType === "checkbox" || sType === "radio"){
if($(formElems[i]).prop("defaultChecked") !== $(formElems[i]).prop("checked")){
changed = true;
break;
}
}else if(sType === "text"){
if($(formElems[i]).prop("defaultValue") !== $(formElems[i]).val()){
changed = true;
break;
}
}
}
if(changed){
$("a#save").css("color","#CCCCCC");
}else{
$("a#save").css("color","black");
}
});
And here is your form
<form id="form1">
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
</form>
The problem is, when one of them change to its original value, it doesn't mean there is no change.
So, in your else code block, you should check all the inputs, if all of them are the original values, remove the 'save' class from the button, otherwise, keep it.
var isChanged = function ($element) {
var sType = $element.prop('type');
if (sType === "checkbox" || sType === "radio") {
var originalCheckedState = $element.prop("defaultChecked");
var currentCheckedState = $element.prop("checked");
if (currentCheckedState !== originalCheckedState) {
return true;
} else {
return false;
}
} else if( sType === "text" ) {
var originalValue = $element.prop("defaultValue");
var currentValue = $element.val();
if (currentValue !== originalValue) {
return true;
} else {
return false;
}
}
};
var $inputs = $('[id*="_boom"]');
var isAnyChanged = function () {
$inputs.each(function () {
if (isChanged($(this))) {
return true;
}
});
return false;
};
$inputs.change(function () {
if (isChanged($(this))) {
$("a#save").css("color","#CCCCCC");
} else if (!isAnyChanged()) {
$("a#save").css("color","black");
}
});

How can I know the duplicate input element value using jquery?

Im new to web dev and jQuery. I have input element binded with blur event.
This is my code:
// this are my input elements:
<input class="input_name" value="bert" />
<input class="input_name" value="king kong" />
<input class="input_name" value="john" />
<input class="input_name" value="john" />
<script>
$(".input_name").bind("blur",function(){
alert(findDuplicate($(this).val()));
})
function findDuplicate(value){
var result = 0;
$(".input_name").each(function{
if($(this).val == value){
result++;
}
});
}
</script>
my main problem is when i change bert to john it returns me 3 result. how would i exempt the event sender from being checked?
Like others have mentioned, you've got a few syntax errors. Also, rather than explicitly iterating over all the inputs, you could just have jQuery find them for you using selectors:
$(".input_name").bind("blur",function(){
alert(findDuplicate($(this).val()));
})
function findDuplicate(value){
return $(".input_name[value='" + value + "']").length - 1;
}
$(".input_name").bind("blur", function () {
alert(findDuplicate(this.value));
})
function findDuplicate(value) {
var result = 0;
$(".input_name").each(function(){
if (this.value == value) {
result++;
}
});
return result - 1;
}
DEMO
Try this (untested):
$(".input_name").bind("blur",function(){
var nth = $(this).index();
alert(findDuplicate($(this).val(),nth));
})
function findDuplicate(value,nth){
var result = 0;
$(".input_name").each(function{
if($(this).val == value && nth != index){
result++;
}
});
return result;
}

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Categories