jquery change value of input created after page load - javascript

I simply need to change the value of the input field which is created on button click. I have tried the below but it gives me undefined error since the element was not there when the page loaded. any ideas?
$('#test').val("test");
I use the below code for click event but I have no idea how to do the same thing for the above one too
$('body').on("click", ".btnx", function() {
//do something
});

$('#test').click(function(){
//code here
});

$('#test').empty();
$('#test').append('test');

There isn't anything like delegated events when you want to set the value of an input that is added out of your control, because there is no event to wait for.
You can wait for the element to come into existance, and set the value when it's there:
var handle = window.setInterval(function(){
var i = $('#test');
if (i.length) {
i.val('test');
window.clearInterval(handle);
}
}, 100);
The interval 100 means that it checks ten times per second, so it may be as long as 1/10th of a second after the element is created that the value is changed. You can adjust the value depending on how fast you need the value to be set, and how much overhead you can allow.

Related

Passing "this" to a function in jQuery problems

sorry but couldn't find a solution for my problem so far.
I am writing a kind of an email template editor as a little task for my boss.
$('a, span').click(function(event){
var editableElement = $(this);
if($(this).is('a')){
event.preventDefault();
}
if(editableElement.is('span')){
processType(editableElement, 'simpleText', modalContent)
When I send the 'editableElement' variable first time, everything's fine, sends object to my function, where I open up a modal window, where there is a textarea, which if i enter text and submit it using only jQuery it will put the text from the textarea (using .val()) to my desired element, in this case a "span" element which is the 'editableElement' using .text() on it. No problem, it works for the first time. After I try to edit a second span, it constantly modifies the previous span too, with whatever I enter in to the textarea (which is cleared out completely, the problem is NOT here) I've ran a fast debug with a simple foreach on the editable element, and the problem is that for some reason it keeps adding objects to the editableElement variable everytime I send it to the function. The number of spans I try to edit, the number of objects will be in my variable all with the index of 0.
Any idea what could be the cause of this?
Thanks in advance!
EDIT:
As requested the whole code in one piece which I have problem with, though it was the whole code before too, I'm in an early stage of writing it, I understand that it was hard to read though, perhaps now it is properly formatted as requested.
$(window).load(function()
{
var modalContent = $('#modalContent');
modalOverlay = $('#modalOverlay');
$('a, span').click(function(event)
{
var editableElement = $(this);
if($(this).is('a'))
{
event.preventDefault();
}
if(editableElement.is('span'))
{
processType(editableElement, 'simpleText', modalContent)
}
});
$('#codeGenButton').click(function()
{
var container = $('#codeContainer');
container.empty();
container.text(getPageHTML());
});
$('#modalClose').click(function()
{
$(this).parent().parent().animate({'opacity': '0'}, 200,
function(){
$(this).css({'display': 'none'});
});
});
});
function fillData(targetDomElement, modalObject)
{
$('#modalSubmit').click(function(){
targetDomElement.text($('#simpleTextEdit').val());
closeModalWindow();
});
}
function processType(targetDomElement, type, modalObject)
{
modalObject.empty();
if(type == 'simpleText')
{
modalObject.append("<p id='simpleTextEditTitle'>Text editor</p><textarea id='simpleTextEdit'></textarea>");
getModalWindow();
fillData(targetDomElement, modalObject);
}
}
Step by step of what it should do:
First of all, the html should not be needed for this, it does not matter, and this is the whole code honestly.
When you click on either an element of (span) or an element of (a) it triggers the function.
It will check if it was actually a (span), or an (a) element.
Currently if it is an element (a), it does nothing, not implemented yet, but if it is a (span), it will call in the processType function, which it sends the "handler?" of the element to namely "editableElement" which has been declared right after the click event, the 'simpleText' which gets send too, is just to differentiate between element types I will send to the processType function later on, and for the last, "modalConotent" is only a div container, nothing more.
Once the function gets the data first, it will make sure, that the modal window gets cleared of ALL data that is inside of it, then it will append a bit of html code as you can see, in to the modal window, which pops up right after I have appended data in to it, it is literally just a 'display: block' and 'animate: opacity: 1' nothing special there.
Lastly it will trigger the 'fillData' function, which will put my desired data from '#simpleTextField' which is only a (textarea) where you can write in, to my desired element 'editableElement' which is the element you have clicked at the first place, a (span) element after the submit, which is again, just a css of 'display: none' and 'opacity: 0' closes the modal window.
THE END.
Your problem is here
function fillData(targetDomElement, modalObject)
{
$('#modalSubmit').click(function(){
targetDomElement.text($('#simpleTextEdit').val());
closeModalWindow();
});
}
Each time this function is called it adds a new click handler with the perameters at the time the handler was created. This handler is added in addition to the already created handlers. See a demo here. After successive clicks on the spans notices how fillData is called multiple times for a single click.
To give you the best possible answer I need to know where your modalSubmit button is in relation to modalContent. Also is is modalSubmit dynamic or static on the page?
Here is a fairly hacky fix in the mean time using on and off to bind and remove the handler respectively:
function fillData(targetDomElement, modalObject)
{
$('#modalSubmit').off("click"); /*Clear Hanlders*/
$('#modalSubmit').on("click", function(){
console.log("fill data");
console.log(targetDomElement);
targetDomElement.text($('#simpleTextEdit').val());
/*closeModalWindow(); Don't have anything for this so ignoring it*/
});
}
Demo
I've solved it myself by using .submit() (of course this means adding form, and an input with the type of submit) instead of .click() when I send the request to modify the element I've clicked on originally.
I don't understand though, why it did what it did when I've used the .click() trigger.

Using a function with an interval to change a class of a div?

I'm trying to create a simple game that has a function that selects a random div(out of a selection)and then sets a random countdown using an interval and when the countdown hits 0 the class of that div will change.
Then i have it so when you click on something assigned with that class it will change back to the original class.
At the moment when i'm running my code the divs seem to be changing after the countdown but won't change when i click them.
But my main problem is that the main function that changes the random divs is only running once.
The divs ("box") start as .wait
My code:
var react = function(){
var box = parseInt(Math.random()*64);
while($("box"+box).hasClass("now")) {
box = parseInt(Math.random()*64);
}
var timer = parseInt((Math.random()*10)+2);
var countdown=setInterval(function(){
timer-=1
$("#box"+box).text(parseFloat(timer.toFixed(0)));
if(timer<=0){
clearInterval(countdown)
$("#box"+box).text("");
$("#box"+box).text("");
$("#box"+box).removeClass("wait");
$("#box"+box).addClass("now");
}
},1000)
}
$(document).ready(function(){
//paint\\
//$(".wait").click(function() {
//$(this).toggleClass("now")
//})
//paint\\
setInterval(react(),1000);
$(".now").click(function(){
$(this).removeClass("now");
$(this).addClass("wait");
})
})
The issue is how you're binding your click event. You'll want to delegate that event, rather than use click().
When setInterval runs, it adds a class, 'new' to an element. However, since no elements had that class name (when calling click() in $doc.ready), no handler is triggered.
First, a fiddle demonstrating this works: http://jsfiddle.net/yvvMp/
Here's an example using your code + delegating the events:
var react = function(){
var box = parseInt(Math.random()*64);
while($("#box"+box).hasClass("now")) {
box = parseInt(Math.random()*64);
}
var timer = parseInt((Math.random()*10)+2);
var countdown=setInterval(function(){
var $el = $('#box' + box);
timer-=1
$el.text(parseFloat(timer.toFixed(0)));
if(timer<=0){
clearInterval(countdown);
$el.text("")
.removeClass("wait")
.addClass("now");
}
},1000);
}
$(document).ready(function(){
$parent = $('.parent-to-now-elements') // $('body') works, but not as efficient
setInterval(react, 1000);
$parent.on('click', '.now', function(){
$(this).removeClass("now");
$(this).addClass("wait");
})
})
Tilwin's answer will work, but you run into the chance that the same element could have multiple event handlers bound. Depending on how long the game runs, and how often a user gets the same DIV element randomly selected, your DOM could look something like:
<div class='wait wait wait wait wait wait wait wait wait'></div>
Worse, each time jQuery calls the click handler, you're forcing the browser to touch the DOM (depending on the game, this could be bad!)
Here's an example: http://jsfiddle.net/pjMcv/
(When a block turns green, click it. Then wait for it to turn red again and click...)
(Tilwin has edited his answer, removing .click out of setInterval. His edited answer is better, but it still has a downside - it requires n number of event bindings. Works for simple games, but if your game has 1000 squares, you'll have 1000 event handlers)
"But my main problem is that the main function that changes the random divs is only running once."
i'm assuming that you're referring to the following line.
setInterval(react(), 1000);
modify it as follows:
setInterval(react, 1000);
update:
assuming you've a fixed number of div, you can assign a common handler for all of them at page load like
$(document).ready(function(){
$('your-common-div-selector').click(function(){
if($(this).hasClass("now")&& !$(this).hasClass("wait")) {
this.removeClass("now");
this.addClass("wait");
});
});

Trigger event on specific condition

I have a div that will serve as container to other element, I have buttons that add element to that div.
Please see the demo for a get an idea about it.
So, what I want to do is to check before adding a new element is the div reached a maximum number of elements that I define, let's say 4.
I can check this condition before every add, but I am sure this is not the best way (we learned that if the code contains copy/paste then is not the best solution) Also, this is just a sample, in my case, I have many buttons..
Is there a way to have a listener like this?
$('#container').bind('divFull', function(){
//My code
});
So that I can disable buttons..
First, you have to listen to DOM change event, then you can trigger a custom event based on the number of children
$('#container').bind('DOMSubtreeModified', function(){
if($(this).children().length>=4){
$(this).trigger('divFull');
}
});
then you can bind to your custom divFull event
$('#container').bind('divFull', function(){
alert('container is full');
$('button').prop('disabled',true);
});
a working demo based on your example
I change a bit the #skafandri method because the event DOMSubtreeModified doesn't work on IE < 9 and it's depreciated.
The main change is to create a function which will call the divFull event if their is 4 children in the container.
var checkFull = function() {
if ($container.children().length === 4) {
$container.trigger('divFull');
}
}
$('#button1').click(function(){
$container.append('<div class="element">some text</div>');
checkFull();
});
Here is the demo.

JQuery - What can I do to make this work?

http://jsfiddle.net/piezack/X8D4M/5/
I need the change created by clicking the button to be detected. At the moment you have to click inside the field and then outside for it to detect any change.
Thanks guys.
The code for the button CANNOT be altered. Good tries so far though.
Was overcomplicating things. Answer http://jsfiddle.net/piezack/X8D4M/56/
Example using trigger:
//waits till the document is ready
$(document).ready(function() {
$('button.butter').click(function() {
var $form6 = $('#FormCustomObject6Name');
$form6.val('Text has changed');
$form6.trigger('change')
});
$('#FormCustomObject6Name').change(function() {
var x = $('#FormCustomObject6Id').val();
$("a").filter(function() {
return this.href = 'http://www.msn.com'
}).attr('href', 'http://www.google.com/search?q=' + x);
alert(x);
});
});
i think that jmar has the right idea...if i understand correctly you want to be able to type whatever in the box and without clicking out of it to have the button change it to the text has changed.
i dont know if that alert is really necessary, but you can do this if the alert is not needed:
http://jsfiddle.net/X8D4M/24/
To trigger the change event simply add a .trigger after setting the value.
Also, you're selector for the link wasn't working so I just changed it to #link.
http://jsfiddle.net/X8D4M/22/

jQuery permanently add class on an event

I have the simple bit of jQuery that adds a class to a paragraph when the value of a hidden input changes to 1:
$(document).ready(function() {
if ($("#acf_success_sent").val() == 1){
$("#acf_verified").addClass('gone');
}
});
As far as I know this should work, but as the value only changes briefly, i think the class is only added until the value changes again, so it's not noticeable. How can I get the class to stick.
Many thanks
Your code shouldn't be doing anything, unless the value is 1 on DOM ready (because that's the only time it will check it). If you want it to check the value constantly, change it to an onchange event.
$(document).ready(function() {
$("#acf_success_sent").change(function(){
if ($("#acf_success_sent").val() == "1"){
$("#acf_verified").addClass('gone');
}
});
});

Categories