Get a variable immediately after typing - javascript

I have this code
<span></span>
and this
<div> variable like a number </div>
and
<script>
$(document).ready(function(){
var x = $('div').html();
$('span').html(x)
});
</script>
I need that every time I change the div value, the span reflects the changes of the div
For example.
If I type 1 in the div, the span should immediately show me number 1
If I type 3283 in the div, the span should immediately show me number 3283
but with this code - I need to create
$("div").click(function(){
var x = $('div').html();
$('span').html(x)
});
I do not want to use .click(function) . in need this function run Automatically
after your answer
I use this code
http://jsfiddle.net/Danin_Na/uuo8yht1/3/
but doesn't work . whats the problem ?

This is very simple. If you add the contenteditable attribute to the div, you can use the keyup event:
var div = $('div'),
span = $('span');
span.html(div.html());
div.on('keyup', function() {
span.html(div.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span></span>
<div contenteditable="true"> variable like a number </div>

here is a demo with input:
html:
<span></span>
<input type="text" id="input01">
js:
$(document).ready(function(){
$( "#input01" ).on('keyup',function() {
var x = parseFloat($('#input01').val());
$('span').html(x)
});
});

How can you edit in div element on browser?
It have to be any input type then only you can edit or change value.
So for that on click of that div you have to show some input/textarea at that place and on change event of that input you can update the value of input in span.
<div id="main-div">
<input type="text" id="input-box" />
</div>
<script>
$(document).ready(function(){
$('#input-box').change(function(){
$('span').html($(this).text)
});
});
</script>

$("input[type=text]").change(function(){
var x = $('div').html();
$('span').text(x)
});
This can be use with textbox or textarea, For div user cannot enter text.
http://jsfiddle.net/uuo8yht1/

.change() will not work with a DIV-element. Since you did not specify how the DIV is updated I would recommend either setting a timer or using .keypress()
Example with timer:
$(function(){
var oldVal = "";
var divEl = $("div");
setInterval(function(){
var elTxt = divEl.text();
if (elTxt != oldVal) {
oldVal = elTxt;
$("span").text(elTxt);
}
}, 50);
});

You need a key listener, jquery provides a .keypress(), Examples are provided on keypress documentation.
I recommend to lookup the combination of .on() and .keyup() with some delay or throttle/debounce either via jquery or underscore.js library.
One of the reason or need for delay is to prevent too many event calls which will affect performance.
Here is an example of code in another question regarding throttle and keyup
Hope this helps.

Related

Trigger onKeyUp from script after input value is changed

I have a few input fields that use onKeyUp="script" to return data the moment something is entered.
As a shortcut, I would like to be able to add a value to one of the fields when data is entered from another location AND trigger the script.
I can use document.getElementById("myID").value = MyValue; to add a specific value to the input box, or .addEventListener(); to watch another input field.
This part works well.
However, I have not been able to trigger anything equivalent to onKeyUp, which will happen either when:
1. You press/release a key while the input field is in focus.
2. You focus the input and release a key AFTER the script has added a value.
3. You enter the input field via [TAB] AFTER the script has added a value.
Adding .keyup(); or .keypress(); have had no effect.
I've been able to use .focus(); to focus and then change the input, but this does not have the same effect as pressing [TAB]
What can I do to trigger the onKeyUp for this field, even if the data was not manually typed?
ADDITIONAL INFO
This part works...
<input type="text" id="box1" onKeyUp="script1();">
<div id="result1" "> (script places result here) </div>
Add value from another location - Option 1
<input type="text" id="Test1">
<button type="button" onclick="TestScript()"> TEST</button>
<script type='text/javascript'>
function TestScript() {
var test1=document.getElementById("Test1").value;
document.getElementById("box1").value = test1;
document.getElementById("box1").keyup();
return false;
}
</script>
Add value from another location - Option 2
<script type='text/javascript'>
window.onload = function () {
document.getElementsByName("box2")[0].addEventListener('change', TestScript2);
function TestScript2(){
var test2=document.getElementById("box2").value;
document.getElementById("box1").value = test2;
}}
</script>
Both of these options will copy the value to the correct location, but I have not been able to get either to trigger the onKeyUp so that the original script realizes something has changed.
Non working Fiddle example: https://jsfiddle.net/mj8g4xa2/4/
Trigger keyup programatically in;
JAVASCRIPT:
Call onkeyup() on the element.
Create a new keyup event and dispatch it using the element. Note: The source here doesn't support IE. Refer this answer for cross-browser support. Also createEvent is deprecated (MDN Docs for reference).
JQUERY:
$("#elem").keyup();
$("#elem").trigger('keyup');
Change events fire only when the input blurs, according to the MDN Docs.
Also, you should have got Uncaught TypeError: element.keyup is not a function error in your console.
var elem = document.getElementById("data");
function triggerKeyUpEvent()
{
var e = document.createEvent('HTMLEvents');
e.initEvent("keyup",false,true);
elem.dispatchEvent(e);
}
function perform()
{
console.log("KeyUp");
}
function add()
{
elem.value = String.fromCharCode(Math.random().toFixed(2)*100).repeat(5);
elem.onkeyup();
triggerKeyUpEvent();
}
<input id="data" onkeyup="perform()">
<button id="add" onclick="add()">Add Random Data</button>
To fix your JSFiddle update the following code:
var elem = document.getElementById("sim1");
function triggerKeyUpEvent() {
var e = document.createEvent('HTMLEvents');
e.initEvent("keyup",false,true);
elem.dispatchEvent(e);
}
function add() {
var sim1=document.getElementById("sim1").value;
document.getElementById("box1").value = sim1;
elem.onkeyup();
triggerKeyUpEvent()
}
by replacing the line elem.dispatchEvent(e) with box1.dispatchEvent(e)
And the line elem.onkeyup() with box1.onkeyup()
Lastly, it would seem that you don't need to call triggerKeyUpEvent as when I removed it, it still works.
Here's the udpated JSFiddle

How to get a substring from the text of an input field and display it to another html element

var str1=$("#account-number").val().substring(0,4);
$("#first-four").html(str1);
I have tried multiple variations and attempts its been a few hours... so I thought I should ask for help...
I want to be able to take the first four characters of an input field with id "account-number" and send it to a div with id "first-four"
On thing to watch out for is change vs input. The first only fires when the input looses focus.
$("#account-number").on("input", function(){
$("#first-four").text(this.value.substring(0,4));
});
<input id="account-number" type="text" />
<div id="first-four"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function(){
$("#account-number").blur(function(){
var accountNmbr = $("#account-number").val().substring(0,4);
$("#first-four").html(accountNmbr);
});
});
JSFiddle: https://jsfiddle.net/Lw4kr4Lq/
$( document ).ready(function() {
$( "#account-number" ).on("input", function() {
var str1 = $("#account-number").val().substring(0,4);
$("#first-four").html(str1);
});
})

jQuery display property not changing but other properties are

I'm trying to make a text editable on clicking it. Below is the code I'm trying. When the title is clicked it shows an input box and button to save it.
<div class="block">
<div class="title">Title</div>
<div class="title-edit">
<input type="text" name="title" value="Title">
<button>Save</button>
</div>
</div>
I have changed other properties like color or changing the text of the elements and its working, but it is not applying the display property or .show()/.hide() function on the title or edit elements.
Below is my jQuery
$(function(){
$('.block').on('click', editTitle);
$('.title-edit button').on('click', saveTitle);
});
function saveTitle(){
var parent = $(this).closest('.block');
var title = $('.title', parent);
var edit = $('.title-edit', parent);
$(title).show();
$(edit).hide();
}
function editTitle(){
$('.title-edit', this).show();
$('.title', this).hide();
}
Here's the jsfiddle
https://jsfiddle.net/ywezpag7/
I've added
$(title).html('abcd');
to the end to show that other properties/functions are working, but just not the display.
For checking the html change on title element you will have to check the source through developer tools cause the title element is hidden.
Where am I going wrong?
Your problem is in the function saveTitle. The first line must stop the event propagation otherwise after this function the editTitle function is called.
The snippet:
$(function(){
$('.block').on('click', editTitle);
$('.title-edit button').on('click', saveTitle);
});
function saveTitle(e){
// this line
e.stopPropagation();
var parent = $(this).closest('.block');
var title = $('.title', parent);
var edit = $('.title-edit', parent);
title.show();
edit.hide();
title.text($('.title-edit input').val());
}
function editTitle(e){
$('.title-edit', this).show();
$('.title', this).hide();
}
.title-edit{
display:none
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="block">
<div class="title">Title</div>
<div class="title-edit">
<input type="text" name="title" value="Title">
<button>Save</button>
</div>
</div>
The issue as mentioned already is that your click events are fighting. In your code, the title-edit class is within the block, so when you click on the save button it triggers events for both clicks.
The easiest and, imho, cleanest way to resolve this is to switch your click event to be called on .title, and .title-edit button. You can also simplify the code beyond what you've got there.
$(function(){
$('.title').click(editTitle);
$('.title-edit button').click(saveTitle);
});
function saveTitle(){
$('.title').show();
$('.title-edit').hide();
$(title).html('abcd');
}
function editTitle(){
$('.title-edit').show();
$('.title').hide();
}
https://jsfiddle.net/ywezpag7/7/
I tried debug your code, and I had seen, that then you click to "Save" button, handled both functions, saveTitle() and editTitle(), and in that order. Therefore, the elements initially hidden, and then shown.

Jquery input value not showing up correctly

I have something very simple to just get an input value.
The code looks like this:
var $a = $('.custom-amount').val();
$('.custom-amount').on('change', function() {
alert($a)
})
And my input:
<div class='custom-amount'>
<input placeholder='Custom Amount' type='text-area'>
For some reason, my alerts are empty. Does anyone see whats going wrong?
Change your selector to $('.custom-amount input'), and get the value after the change event is fired, e.g.
$('.custom-amount input').on('change', function() {
var a = $(this).val();
alert(a);
});
Right now, you are trying to get the value of a div, which won't work. You need to get the value of the input.
Edit: also, it looks like you are trying to display a textarea. Try replacing this...
<input placeholder='Custom Amount' type='text-area'>
With this...
<textarea placeholder='Custom Amount'></textarea>
This may help:
http://jsfiddle.net/d648wxry/
The issue is very simple, you are getting the value of the div element. Instead you should retrieve the value of the input element so the 'custom-amount' class must be added to the input.
Also you need to execute the val() method inside the event to get the value updated.
var $a = $('.custom-amount');
$('.custom-amount').on('change', function() {
alert($a.val());
});
Cause your div has no value. Change your code to:
var $input = $('.custom-amount input');
$input.on('change', function() {
var $a = $input.val();
alert($a)
})
First of all, you only assign to $a outside of the change function. This would be more clear if you kept your code lined up better (see the edit I made to your post). This is the right way to do it:
$('.custom-amount').on('change', function() {
var $a = $('.custom-amount').val();
alert($a)
});
Second of all, the class custom-amount is assigned to a <div> instead of the <input> element. You have to select the <input> element, not the <div>. Change your markup to:
<div>
<input placeholder='Custom Amount' type='text-area' class='custom-amount'>
</div>

Append a div outside of the input parent

Im fairly new to javascript and I just can't figure this out despite my attempt in researching. How do I track the change of a input within a div and trigger an append to an outside div? My code goes as follow:
Append h3 with "Pending" once ".image-value" input has a change in value
<!-- APPEND <h3> -->
<h3>Best Overall Costume<div class="pending">Pending</div></h3>
<div>
<div class="select-form">
<img src="images/vote.jpg" data-value="image_value">
<img src="images/vote.jpg" data-value="image_value2">
<img src="images/vote.jpg" data-value="image_value3">
<img src="images/vote.jpg" data-value="image_value4">
<img src="images/vote.jpg" data-value="image_value5">
<!-- Track the change of this input -->
<input type="hidden" class="image-value" name="selected_image" value="">
</div>
</div>
I tried this:
function changeStatus(statusValue) {
$("input",".select-form").val(statusValue).trigger("change");
}
$("input",".select-form").change(function(){
if (!$(this).val()){
$("<div class='pending'>Pending</div>").appendTo($("h3").prev($(this)));
}
});
But that didn't seem to work. Any ideas?
place an empty div where you want your new div and give it an id i.e(<div id='myDiv'><div>) and then append what you want like this.
$( "#myDiv" ).append( "<div class='pending'>Pending</div>" );
You can also check Append Explained
for more explanations.
Thanks.
I've done a couple things here... First, I'm not sure why you had it all in a named function. When you're using event listeners that often isn't necessary.
Then, I don't know what the val check was for, so I reversed it.
Finally, I'm using one(), which only runs once. This case seemed to call for that.
$('.select-form').one('change', 'input', function () {
if ( $(this).val() ) { alert('asdgf');
$("<div class='pending'>Pending</div>")
.appendTo($(this).parent().prev('h3'));
}
});
Fiddle
try this:
$("input",".select-form").on("change", function(){
var $this = $(this);
if (!$this.val()){
var elem = $('<h3>Best Overall Costume<div class="pending">Pending</div></h3>');
$this.parent().parent().before(elem);
}
});
you can also place a check, that if the pending div is already added, not to add it again.
Of course this solution assumes that there are no other nested divs between the target div(before which you want to append) and the input control

Categories

Resources