How to react on input text events in jquery? - javascript

I'm trying to react on <input> events with jquery, to modify a background label in as soon as the input contains text:
$('#inpt').on('input', ':text', function() {
Window.alert("test");
$('#mytext').attr('background', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input id="inpt" type="text" placeholder="Type in here" />
</div>
<span id="mytext" style="background:green">Test</span>
Result: nothing happens. I don't even get the alert. Why?

The problem here that you use selector inside you on function cause the $('#inpt') is the container for looking the selector. But in this case the container is the selector (:input) you define in on() function too then it doesn't work and the Window wrong typo too.
attr is use to update the attribute of the element and background is not included inside attr list. Then you should wrap the background: red inside style attr or using css({background:red})
$('#inpt').on('input', function() {
window.alert("test");
$('#mytext').attr('style', 'background:red');
});

You should use with document and keyup
$(document).on('keyup', '#inpt', function() {
alert("test");
$('#mytext').css({'background': 'red'});
});

Related

Clone dynamic content by class

I have a div which shows result of a quotation form. Results changes if user change form value instantly. I want to display or copy the same results of that div to another div or more like a "second version" of that div.I know this below sort of code will work.
$("div1").clone().appendTo("div2");
But it works only for the 1st time page loads. After that it doesn't change the results with the div1 results.
Does anyone have a hint on what to do here?
Many thanks in advance!
Use the onchange event in your html on the form. Then call your code from it somewhat like:
onchange="$('div1').clone().appendTo('div2');"
or
onchange="someJSfuncion();"
also dont forget to delete the old copy. Further information:
https://www.w3schools.com/jsref/event_onchange.asp
You need to setup your event handlers on form changes and then copy the output to other div. Example:
// Original js
(function() {
$('.inp_name').on('change', function() {
$('.original-output .name_text').text($(this).val());
});
})();
// Your js
(function() {
var version = 0;
$('.inp_name').on('change', function() {
version++;
// Don't use clone as your events starts working in cloned code also which you don't expect
//$('.original-output').clone().appendTo('.copied-output');
$('.copied-output').append($('.original-output').html());
$('.copied-output').append(`<div>Version: ${version}</div>`);
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: Focus out see text getting change.
<div class="original-form">
Enter text here: <input type="text" class="inp_name" placeholder="enter your name" />
</div>
<div class="original-output">
Entered name: <span class="name_text">Entered Name</span>
</div>
<div class="copied-output">
</div>

Displaying command as text

My code:
var element = '<button>'+text+'</button>';
$('#output').append(element+"\n");
HTML
<textarea id="output" readonly></textarea>
I want it so the element (button) display in textarea as text not element. I want it to display:
'<button>Hi</button>'
if text = "Hi"
Any ideas ?
Use .val() instead of .append():
$('#output').val(element+"\n");
As mentioned in the other answer, use val() but you want to get the existing value before overwriting it. The reason for this answer being posted is due to the other one not being updated.
Working Demo
$("#Example").on( "click", function() {
//Add new input before existing content
$('#output').val($('#input').val()+"\n"+$('#output').val());
//Add new input after existing content
//$('#output').val( $('#output').val() +$('#input').val()+ "\n");
$('#input').val('');
$('#input').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="input"/><button id="Example">Add</button><br/>
<textarea id="output" readonly></textarea>
JS Fiddle Demo
To preset the text into a button you can wrap the button tags around the input value.
Example: "<button>"+$('#input').val()+"</button>" JS Fiddle Demo 2
Demo Two
$("#Example").on( "click", function() {
//New input before existing content
$('#output').val("<button>"+$('#input').val()+"</button>\n"+$('#output').val());
//New input after existing content
//$('#output').val( $('#output').val() +"<button>"+$('#input').val()+ "</button>\n");
$('#input').val('');
$('#input').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="input"/><button id="Example">Add</button><br/>
<textarea id="output" readonly></textarea>
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!

Change label text for multiple inputs

I have a dynamic page that can have a lot of input[type="file"] fields. I need to change the label of every input once a file is selected.
So, for each input, if:
Empty: text = "upload";
File selected: text = name of file.
Here is a sample of HTML:
<label for="upload-qm1">
<span class="button">upload</span>
<input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>
I know how to do this for a single input, using this code:
$('label[for="upload-qm1"] span').text($(this).val());
However, I don't know how many input fields I will have on my page. I tried something like this:
$(this).parent('label').find('span').text($(this).val());
but unfortunately it doesn't work. Any help on how I can get a method for changing all input fields?
You can use DOM traversal to find the span related to the input which was changed. Try this:
$('input:file').change(function() {
$(this).prev('span').text($(this).val());
})
Working example
The most of the code you tried ist corret.
The problem is that you have set a parameter for the parent() function.
Try something like this:
$(this).parent('label').find('span').text($(this).val());
Also make sure that $(this) is the input field not the label itself,
if you click on the label $(this) is the label.
$('input[type="file"]').on('change', function() {
id = $(this).attr('id');
console.log("change event")
var file = $('#'+id).val().split('\\').pop();
if(file!='') {
$('label[for="'+id+'"] span').text(file)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="upload-qm1">
<span class="button">upload</span>
<input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>

Chaining methods to a newly inserted element via append

While trying to find a solution to this problem I came across this post which suggests using the appendTo method like so:
$('<input[type="text"]').appendTo('div').addClass('foo');
There are times where I'm using append more than the former. Is there a way I can chain methods to a newly inserted element using append?
HTML
<div id="foo">
<input type="text" />
</div>
JS
Add new element
$('body').on('click', 'a', function(e) {
e.preventDefault();
$('div').append('<input type="text" />').addClass('bar');
});
If you still want to use append you can pass jQuery object to it instead of HTML:
$('div').append($('<input type="text" />').addClass('bar'));
$('div').append($('<input type="text" />').addClass('bar'));
.bar {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

How can I select the first specific class after element in jQuery

I need to count the characters of the content in textarea and show it at the below in a specific class.
I'm using the code below which doesn't work for me:
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$(".messageText").each(function(){
$(this).next(".messageCharacters").text($(this).val().length);
$(this).next(".messagePages").text(($(this).val().length / 70).toFixed());
});
$(".messageText").keyup(function(){
$(this).next(".messageCharacters").text($(this).val().length);
$(this).next(".messagePages").text(($(this).val().length / 70).toFixed());
});
});
</script>
<p>
<textarea name="title1" class="messageText">phrase1</textarea>
<br /><span class="messageCharacters">0</span> characters - <span class="messagePages">0</span> pages
</p>
<p>
<textarea name="title2" class="messageText">phrase2</textarea>
<br /><span class="messageCharacters">0</span> characters - <span class="messagePages">0</span> pages
</p>
How should I fix it?
First of all your $(".messageText").keyup(function(){ is outside the document.ready function, therefore your .messageText element are not collected by the DOM parser.
Also .next() element is <br> so either you need to target a parent container or do a .nextAll() like:
$(function(){ // DOM ready shorthand
function count() {
$(this).nextAll(".messageCharacters").text(this.value.length);
$(this).nextAll(".messagePages").text((this.value.length/70).toFixed());
}
$(".messageText").each(count).on("input", count);
});
to prevent one copy-pasteing text inside your textarea (using mouse right click - paste) and your script doing nothing use .on("input") to register any change inside the textarea value listener.
Also think about ($(this).val().length/70).toFixed() if initially 34 characters makes it pages=2 only at 105 you'll get pages=3. So review that math again.
jsBin demo
The element next to your .messageText is the br, so $(this).next(".messageCharacters") will never return your element.
Use .nextAll() instead :
$(this).nextAll(".messageCharacters")
Change $(this).next to $(this).siblings

Categories

Resources