.on detects only first change - javascript

Trying to pass changes in input field to a variable simultaneously with the change. But for some reason, my code detects only first change. For example, if I enter "100" into the field, it only detects "1". Nothing happens afterwards.
Here is my jquery
$(document).ready(function() {
var wholeshort = $(".shorcodeval").val();
a = wholeshort;
var w = /width="(.*?)"/.exec(a)[1];
$(".widthinput").on('input', function() {
nw = $(this).val();
wholeshort = wholeshort.replace(w, nw);
$(".shorcodeval").val(wholeshort);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="widthinput" />
<textarea class="shorcodeval">[example width="300px"]</textarea>
here is the fiddle
https://jsfiddle.net/3a6n1fux/

The problem is that after the first input you save [example width="1"] in wholeshort, but w is 300px so you try to replace 300px in [example width="1"].
To solve that you would need to save the result of wholeshort.replace(w, nw) in an own variable or pass it directly to .val(wholeshort.replace(w, nw)).
$(document).ready(function() {
var wholeshort = $(".shorcodeval").val();
var w = /width="(.*?)"/.exec(a)[1];
$(".widthinput").on('input', function() {
var nw = $(this).val();
$(".shorcodeval").val(wholeshort.replace(w, nw));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="widthinput" />
<textarea class="shorcodeval">[example width="300px"]</textarea>

Related

Jquery - Variable not updating into another variable

first of all i'm not a programmer of any kind, so i please need you to fix my issue.
I have a contact form which have inside a place where i can add more input fields till a maximum of 10.
Each field i add it has inside the code a class that i called "pers", and i want that this class pers has an incremental number near to it, as pers1, 2, 3 and so go on.
Getting the incremental value was easy but the problem is that the class "pers" wont update the variable keeping the first number on document load.
Here is the code
<script type="text/javascript">
window.s = 1;
</script>
<script type="text/javascript">
$(document).ready(function() {
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var maxField = 10;
var fieldHTML = '<div style="margin-top:5px;"><input type="text3" name="pers' + window.s + '" placeholder="Nome e Cognome"/><input type="time" style=margin-left:3.5px; autocomplete="off"><input type="time" style=margin-left:3.5px; autocomplete="off"><img src="IMG/less_icon.png"></div>';
$(addButton).click(function() {
if (window.s < maxField) {
window.s++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
s--; //Decrement field counter
});
});
</script>
There is a global variable "window.s" because it was my last try to get the var updated.
The fields adds correctly till 10 as it should be, but the "window.s" or when it was only "s" still keeps his first value of 1, and so "pers" is always "pers1". I thought that exposing a global variable i would have fix the problem, but nothing.
What am i doing wrong?
Thank you very much for your help guys.
The problem with your code is because you only set fieldHTML once, when the page loads. At this point window.s is 1, so this is the value that's used every time you reference fieldHTML. The quick fix to this would be to put the fieldHTML definition inside the click() event handler.
However the better approach it to entirely remove the need for the incremental variable at all. Use the same name on all the fields you dynamically generate. This way you don't need to maintain the count (eg. if there have been 5 added and someone deletes the 3rd one, you'll currently end up with 2 per5 elements). Because of this it also simplifies the JS logic. In addition you should put the HTML to clone in a <template> element, not the JS, so that there's no cross-contamination of the codebase.
Here's a working example of the changes I mention:
jQuery($ => {
var $addButton = $('.add_button');
var $wrapper = $('.field_wrapper');
var maxFields = 10;
var fieldHTML = $('#field_template').html();
$addButton.click(() => {
if ($('.field_wrapper > div').length < maxFields) {
$wrapper.append(fieldHTML);
}
});
$wrapper.on('click', '.remove_button', e => {
e.preventDefault();
$(e.target).closest('div').remove();
});
});
.field_wrapper>div {
margin-top: 5px;
}
.field_wrapper input.time {
margin-left: 3.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button class="add_button">Add</button>
<div class="field_wrapper"></div>
<template id="field_template">
<div>
<input type="text3" name="pers[]" placeholder="Nome e Cognome" />
<input type="time" name="time1[]" class="time" autocomplete="off" />
<input type="time" name="time2[]" class="time" autocomplete="off" />
<a href="#" class="remove_button" title="Rimuovi">
<img src="IMG/less_icon.png">
</a>
</div>
</template>
You can then receive all the input values as an array in your PHP code, like this.
It's because you have not used the updated value there.
First, you assign a value to window.s, and then you create a variable that uses the value of window.s from the initial state, and on each addition, it just appends the same fieldHtml. So, you are getting the same value.
Here is the answer, you are looking:
<div><button class="add_button">click me</button></div>
<div class="field_wrapper"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
window.s = 1;
</script>
<script type="text/javascript">
$(document).ready(function() {
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var maxField = 10;
$(addButton).click(function() {
if (window.s < maxField) {
window.s++; //Increment field counter
let fieldHTML = generateLine(window.s);
$(wrapper).append(fieldHTML); //Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
s--; //Decrement field counter
});
});
function generateLine(lineNumber){
return '<div style="margin-top:5px;"><input type="text3" name="pers' + lineNumber + '" placeholder="Nome e Cognome"/><input type="time" style=margin-left:3.5px; autocomplete="off"><input type="time" style=margin-left:3.5px; autocomplete="off"><img src="IMG/less_icon.png"></div>';
}
</script>

Get value from input field while typing, using javascript

I am trying to set 2 variables with values from input fields and use them to calculate area.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form>
<label for="fname">Height:</label>
<input type="text" id="boxHeight" name="fname"><br><br>
<label for="lname">Width:</label>
<input type="text" id="boxWidth" name="lname"><br><br>
</form>
</body>
</html>
//var l = jQuery('#boxWidth').find('input'); ---> does not work
//var h = jQuery('#boxHeight').find('input'); ---> does not work
var l = document.getElementById("#boxWidth");
var h = document.getElementById("#boxHeight");
var a = parseInt(l);
$(document).on("change paste keyup", "#boxWidth, #boxHeight", () => {
console.log("text "+a);
});
The code can be tested here get input to integer
Nothing seems to work. Any suggestions?
You have a number of small issues getting the right input, and the value from those inputs.
$(document).on("change paste keyup", "#boxLatime, #boxInaltime", () => {
var boxLatime = document.getElementById("boxLatime");
var boxInaltime = document.getElementById("boxInaltime");
var l = parseInt(boxLatime.value) || 0;
var h = parseInt(boxInaltime.value) || 0;
vr_do_l_h(l, h);
});
https://jsfiddle.net/dvtc9brq/

Increment input field value with jQuery

I want every time when user enter number ,print the new one + old one in console
here is html script
<input type="number"value=""/>
<button>click</button>
my jquery code
$("button").click(function (){
var x = $("input").val();
x+=x;
console.log(x);
});
You have to initialize the value outside somewhere to keep its state.
html
<input type="number" id="inp" value=""/>
<button>click</button>
js
var x = 0;
$("button").click(function (){
var y = parseInt($("#inp").val());
x+=y;
console.log(x);
});
hope this will help to you. refer the working demo.
var thevalue = 0;
$("#click").click(function(){
$("#display").text("The Value is :");
var theinput_value = parseInt($("#num").val());
thevalue += theinput_value;
$("#display").append(thevalue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button>
<br>
<p id="display">The Value is :</p>
You just need to make sure x is a global variable so you can save it's value and used each time the click handler is triggered.
I added input casting to avoid string concatenation when using the addition assignment operator.
var x = 0;
$("button").click(function (){
// Get the input
var current_input = parseInt($("input").val());
// If input is not a number set it to 0
if (isNaN(current_input)) current_input = 0;
// Add the input to x
x+=current_input;
// Display it
console.log(x);
});

Jquery :How to store textbox value clientside and display?

The below code will update the display value enter by user in textbox when button clicked but in this code it will not preserve the previous value enter by user .
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="textDiv"></div> -
<div id="dateDiv"></div>
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#textDiv").text(value);
$("#dateDiv").text(new Date().toString());
});
});
Now I want preserve all the value enter by user and when user will submit the button show both value previous as well as current.
How to achieve this ?
Can below code will help to preserve all the value
var $input = $('#inputId');
$input.data('persist', $input.val() );
If yes how to display all value previous,current etc. when user click on button ?
If i got this right, this is what you need?
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<script type="text/javascript">
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#section").prepend('<div class="textDiv">'+value+'</div>')
$("#section").prepend('<div class="dateDiv">'+new Date().toString()+'</div>')
$("#txt_name").val('');
});
});
</script>
<!-- each time you press submit, a new line will be pushed here -->
<div id="section">
</div>
If you want to display only the previous and current value the user submitted and use the data function then:
$("button").click(function() {
var input = $("#txt_name").val();
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',input);
$("#dateDiv").text(new Date().toString());
});
If you want all the values and you want to store them, then I would create an array. But you could always concatenate the string.
var arr = [];
$("button").click(function() {
var input = $("#txt_name").val();
arr.push(input);
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',previous+input);
$("#dateDiv").text(new Date().toString());
});
Without using .data() you can do this:
$("button").click(function() {
var input = $("#txt_name").val();
$("#textDiv").text($("#textDiv").text()+input);
$("#dateDiv").text(new Date().toString());
});
Instead of using two separate divs for message and date, you can use a single div.
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="msgDiv"></div>
$(document).ready(function() {
var preservedTxt = '';
$("button").click(function() {
var input = $("#txt_name").val();
var date = new Date().toString();
var msg = input + ' - ' + date;
preservedTxt = preservedTxt + '<br>' + msg;
$('#msgDiv').html(preservedTxt);
});
});
Jsfiddle : https://jsfiddle.net/nikdtu/p2pcwj2f/
Storing values in array will help
jQuery(function(){
var name=[];
var time=[];
$("button").click(function() {
var value = $("#txt_name").val();
name.push(value);
$("#textDiv").text(name);
time.push(new Date().toString())
$("#dateDiv").text(time);
});
});

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Categories

Resources