Jquery :How to store textbox value clientside and display? - javascript

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);
});
});

Related

.on detects only first change

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>

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

Sum Cookie value when I click a button

I have an input text and a button where a I put a number and storage this value in a Cookie using js-cookie clicking a button.
<input id="number" type="text" value="0">
<button id="send" type="button">SEND</button>
I want to sum each time I enter a number and show the result in an alert, so I tried in this way:
Jquery:
$("#number").keypress(function(e){
if(e.keyCode==13){
$("#send").click();
}
});
$("#send").click(function(){
var number= 0;
number+= parseInt($("#number").val(),10);
Cookies.set("numw", number);
});
var numw = Cookies.get("numw");
alert("Total: "+numw);
But this still showing the first number I sent.
I would like some help.
All you need is to add the number like:
$("#send").click(function(){
//var number= 0;
var numwTemp = Cookies.get("numw");
//number = parseInt($("#number").val(),10)) + parseInt(numwTemp, 10);
var number = parseInt($("#number").val(),10)) + parseInt(numwTemp || "0", 10);
Cookies.set("numw", number);
});
var numw = Cookies.get("numw");
alert("Total: "+numw);

How to apply keypress and mousedown event on dynamically created textbox

I am working in an application where i have three textboxes dynamically polulated,one is for input value 2nd one is for a time and 3 rd one is also for a time both 2nd and 3 rd boxes have timepicker api in it.So now what i need i will type something in the textbox and also select time from those two timepicker boxes and values will be appending on the respective textboxes on top of them.Like i am giving a fiddle where i have implemented the situation i have reached so far,This is it DEMO
So i will write something on textbox1 and that will be that will be showing on textbox on top of it and also i will select a time from 2 nd box and 3 rd box and that will be on the 2 nd and 3 box on top of that.I am trying to use keypress and mousedown but that is not working on dynamic population of the textboxes like i tried using
$('#TextBoxContainer').on('keypress', 'input', function () {
});
But this is not giving the value of the textboxes .Somebody please help
Try this code.
Note : I used comma to separate the values from different text boxes.
Demo
HTML
<input id="text1" type="text" value="" />
<input id="text2" type="text" value="" />
<input id="text3" type="text" value="" />
<div id="TextBoxContainer">
<input id="btnAdd" type="button" value="Add" />
</div>
JS
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
$(".time").timepicker();
$('.txt1,.txt2,.txt3').change(function () {
UpdateData()
});
});
$("#btnGet").bind("click", function () {
var valuesarr = new Array();
var phonearr = new Array();
var phonearr1 = new Array();
$("input[name=DynamicTextBox]").each(function () {
valuesarr.push($(this).val());
$('#DynamicTextBox').val(valuesarr);
});
$("input[name=phoneNum]").each(function () {
phonearr.push($(this).val());
$('#phoneNum').val(phonearr);
});
$("input[name=phoneNum1]").each(function () {
phonearr1.push($(this).val());
$('#phoneNum1').val(phonearr1);
});
alert(valuesarr);
alert(phonearr);
alert(phonearr1);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input class="txt1" name = "DynamicTextBox" type="text" value = "' + value + '" /> <input class="txt2 time" id="myPicker" class="time" type="text" /> <input name = "phoneNum1" id="phoneNum1" class="time txt3" type="text" /><input type="button" value="Remove" class="remove" />';
}
function UpdateData() {
var text1 = ''
$('#TextBoxContainer').find('.txt1').each(function (index, Obj) {
if ($(Obj).val()) text1 += $(Obj).val() + ','
})
$('#text1').val(text1)
var text2 = ''
$('#TextBoxContainer').find('.txt2').each(function (index, Obj) {
if ($(Obj).val()) text2 += $(Obj).val() + ','
})
$('#text2').val(text2)
var text3 = ''
$('#TextBoxContainer').find('.txt3').each(function (index, Obj) {
if ($(Obj).val()) text3 += $(Obj).val() + ','
})
$('#text3').val(text3)
}
If I understood you correctly, you don't need processing keypress and mousedown events.
You just need to process onsubmit event of your form. Just read values from textbox, DateTimeBox, DateTimeBox and paste them to newly created textbox2, DateTimeBox21, DateTimeBox22.
In case you want to create dynamicly 3 input boxes with the value of text1 text2 and text3 here is the result.
And this is pretty much what i've changed:
...
$("#btnAdd").bind("click", function () {
var a = $("#text1");
var b = $("#text2");
var c = $("#text3");
var div = $("div");
div.html(GetDynamicTextBox(a, b , c));
...
Obviously in GetDynamicTextBox() function i'm filling the InputBoxes with the expected values (from a, b and c).
In case you want to update text1 text2 and text3 with the values of the generated input boxes this would do it:
here is the relevant code i've changed on this one:
$('.txt1').bind('keyup',function(e){
var code = e.which;
if(code==13)e.preventDefault();
if(code==32||code==13||code==188||code==186){
$('#text1').val($('#text1').val()+', '+$(this).val());
}
});
For the above solution to work, you've got to press enter after changing each input box.
In case you preffer to not press enter here you've got a solution which works when the generated input box loses the focus.
This is the relevant code:
$('.txt1').bind('focusout',function(){
$('#text1').val($('#text1').val()+', '+$(this).val());
});
You might want to check if the new value is the same that the old one or not in this one.
PS: I'm showing here the snippet of just the first inputbox since for the rest of them is pretty much the same. The complet solution is in the jsfiddle though.

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

Categories

Resources