dynamic input on change jquery - javascript

I have a dynamic input field which is being generated like this
var field = '<tr><td><input type="text" name="program_id" data-id="'+val['program_id']+'" value="'+val['program_id']+'">'+programBtn+'</td></tr>';
$('#transaction').append(field);
$('#transaction').on('change', 'input',function() {
console.log('hi');
});
And i have a button that when i click, it will input data into that input field using
$('.button').on('click', function() {
var text = $(this).data('text');
var id = $(this).data('id');
$('#transaction').find('input:'+id).val(text);
});
Ok if i click the button it will fill in those values but console.log('hi') isnt firing. But if i type in the text box and then i leave focus it, i can see console.log('hi') is firing. Note that code here is just an example.
My Jquery version is 3.2.1

You need to trigger change function as soon as you change the input value since change fn will be triggered only when the user changes the value manually and losses the focus.
you can trigger that using .trigger('change') or change()
var field = '<tr><td><input type="text" name="program_id" data-id="11" value="test"></td></tr>';
$('#transaction').append(field);
$('#transaction').on('change','input',function() {
console.log('hi');
});
$('button').on('click', function() {
var text = $(this).data('text');
var id = $(this).data('id');
$('#transaction').find('input[data-id="'+ id +'"]').val(text).change();
//$('#transaction').find('input[data-id="'+ id +'"]').val(text).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="transaction">Transaction: </div>
<button data-text="Some Text" data-id="11">Click</button>

I think you're finding input element that has data-id with value equal to data-id on the clicked button. If that so, you might use
$('#transaction').find('input[data-id="+ id +"]')
And from previous topic. onchange only fires when the user types into the input and then the input loses focus. So, you need to trigger the event manually.
$('.button').on('click', function() {
var text = $(this).data('text');
var id = $(this).data('id');
$('#transaction').find('input[data-id="+ id +"]').val(text).change(); // trigger change event
});

Related

jQuery blur() appears on focus

I want to validate each input of a form on blur() so if user leaves the input box.
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
alert("Validate: " + input);
});
It works fine but when i'm in the first input field and hit TAB to get to the next input field,
my script straight validate the second input.
But I want only to validate if i leave the inputs.
JSFiddle
The alert is causing the object to lose focus triggering the blur. Use Console.log() to test instead:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id'); // This is the jquery object of the input, do what you will
console.log("Validate: " + input);
});
Your code seems to be working fine!!!
But Instead of the alert you must need to use console.log().If you are
using alert then it will continuous call blur function because you are
trying to close the alert box and at that time it will call blur
event.So it's something like circular function.
Instead of:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
alert("Validate: " + input);
});
It should be:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
console.log("Validate: " + input);
});

Check if textbox goes empty after having a value without submitting form or pressing outside of the textbox

I have a currency exchange in my backend, I post data from my textbox to the currency exchange using ajax and view the exchanged value in a label, which is otherwise hidden.
The problem is, if I enter a value in the textbox, and then erase the value from the textbox, the latest value is still there ( I want to hide the label again when the textbox is empty )
This is the code I've tried so far:
$('#transferAmount').on('change',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();
}
});
I've tried with "on-input" aswell, but it didn't work. Does anyone have a good solution to this?
Use input event instead of change event as change event handler will only be invoked once focus in the input field is lost.
The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed.
$('#transferAmount').on('input', function() {
var amount = $(this).val();
$('#amountExchangedHidden').toggle(!!amount.length);
}).trigger('input'); //`.trigger` to invoke the handler initially
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id='transferAmount'>
<input type="text" id='amountExchangedHidden'>
Use blur Event instead of Change
$(function) {
$('#transferAmount').on('blur',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();}
});
});

Alert toggles every time when the input is changed

I have input and it toggles a function if it's been changed. I also have table that is created dynamically. And each row in table has an addButton. So, the problem is that this alert toggles so many times so I change the input, but I need to toggle it only once. How to deal with it?
$('.inputsearchform').bind('input', function() {
var addButton = $(".fa.fa-plus");
addButton.click(function() {
alert("test");
});
});
I don't need to add click event to this button, but I need to get onclick() event from it. But this code is only working way, that I found. By the way, I need to get this event only if button is clicked, not every time that I change input.
Question How to check onclick event on button, that appears dynmically, when the input changes?
I tried to add onclick event <i class="fa fa-plus" onclick="addButtonF()">
and in js file: function addButtonF(){
alert("test");
}
but I have an error addButtonF is not defined.
A start would be to define click outside of input handler to prevent multiple click handler calls at each click of addButton
So, the problem is that this alert toggles so many times so I change
the input, but I need to toggle it only once.
Not clear from Question which element needs to be toggled once, or which function should only be called once ?
addButton appears only if I write something in input. I need to use
alert only if I click on this button, not every time that I change
input.
Use event delegation to attach event to dynamically created elements having className .fa.fa-plus
$(".inputsearchform").bind("input", function() {
// create dynamic element
$("<table class='fa fa-plus'>")
.html("<tr><td>"
+ $(".fa.fa-plus").length
+ "</td></tr>"
).appendTo("body");
});
$(document).on("click", ".fa.fa-plus", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
Substitute className for class which does not set className of element; use latest version of jQuery
$(".inputsearchform").bind("input", function() {
var div = document.getElementById("div");
var table = document.createElement("table");
div.appendChild(table);
var tr = document.createElement("tr");
table.appendChild(tr);
var td = tr.insertCell(0);
td.innerHTML = "test";
td.className = "try"
});
$(document).on("click", ".try", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
<div id="div"></div>
jsfiddle https://jsfiddle.net/1x8ja6qe/2/

Check if input value is not the same onBlur

How can I check if the value of an input box is not the same after blur?
$("#username").on('blur', function() {
$("#usertext").append("new input<br>");
})
Check this jsFiddle: https://jsfiddle.net/xztptsdg/
Let's think that I enter "Josh" in input and after blur, will append new input box. But, user can "re-blur" the username input, and will append other input.
I want to check if the value is the same, not append new input.
You may use change instead of blur, for example:
$("#username").on('change', function() {
$("#usertext").append("new input<br>");
});
So, there is no need to check if the value changed or not because the change event is sent to an element when its value changes.
See this fiddle
You can keep a global variable to store the current value of the textbox and then check whether the entered value is the same as the previous one. If not, then append the new input text and also set the global variable with the new one. Below is the Javascript that does this.
JS
var txt = "";
$("#username").on('blur', function() {
if (txt != this.value) {
$("#usertext").append("new input<br>");
txt = this.value;
}
})
I would suggest you to use change(). According to the docs
The change event is sent to an element when its value changes.
See the fiddle and below is the JS code with change().
$("#username").change(function() {
$("#usertext").append("new input<br>");
});
You can do it like following snippet.
var text = '';
$("#username").on('blur', function() {
if(this.value != text){
text = this.value;
$("#usertext").append('new input<br>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="username" id="username">
<br>
<span id="usertext"></span>

Changing input value on input, without affecting change listener?

I have a text input. It has a change and an input listener. In the input listener, I delete the value of the input, if it is "delete". The change listener simply alerts "Changed.".
Current behaviour:
There is no "Changed." alert when I type "delete" and stop editing, because the comparison base is changed as well.
Desired behaviour:
I want to see the "Changed." alert based on the value at the start of the editing, ignoring all the programatic changes made during the modification.
What is the simplest way of doing this?
Playgorund:
Click the input.
Delete the content.
Type "delete".
See how the text is deleted.
Click somewhere else.
See how the "Changed." alert is not displayed.
var input = document.querySelector('input');
input.addEventListener('change', function() {
alert('Changed.');
});
input.addEventListener('input', function() {
input.value = input.value.replace(/^delete$/, '');
});
<input value="example" />
My current solution is to add an attribute that I store the initial value in on each focus event, and compare it to the current value at the time of the blur event.
var input = document.querySelector('input');
input.addEventListener('focus', function() {
this.setAttribute('data-value-on-focus', this.value);
});
input.addEventListener('blur', function() {
if (this.getAttribute('data-value-on-focus') !== this.value) alert('Changed.');
});
input.addEventListener('input', function() {
this.value = this.value.replace(/^delete$/, '');
});
<input value="example" />

Categories