jQuery Click event not firing on element click [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
Below is my html and javascript. The Js is located in a app.js file and the html is a yes or no question. At the bottom of the javascript I have code that should fire on click events. Right now it is just to see if it detects a click on the p elements in the html but hasn't worked so far.
Can anyone detect why this event isnt taking place?
The other jQuery int he code does work but this jQuery isnt invoked by a function and is invoked based of strictly using a selector which leads me to believe there is something wrong with how I used document.ready in my project.
Html:
<div class="question animated slideInUp">
<h3>Do you know your individual monthly rent cost?</h3>
<div class="rentanswer">
<p>Yes</p><p>No</p>
</div>
<!--
<p>If not, we'll get the average rent of a zip code for you from Zillow</p>
<form onsubmit="Obj(this.p.name,this.p.value)">
<input type="number" id="p" name="rent" placeholder="Leave blank if N/A" >
<input id="s" type="submit" value="Submit">
</form>
-->
</div>
Javascript:
var quest = ['../partials/income.hbs', '../partials/state.hbs', '../partials/rent.hbs', '../partials/zip.hbs', '../partials/roomate.hbs', "../partials/summary.hbs"];
var iterator = 0;
//creates object that gets sent to api
function Obj(name, vale){
event.preventDefault(); //prevents pg refresh
$('.form').load(quest[iterator], function () {
$('.bar p#' + name).css("border","2px solid black").addClass('enter').next().css({"border":"2px solid black","pointer-events":"auto","cursor":"pointer"});
});
//loads next html question to page
if(name){
data[name] = vale;
}
//move array accessor up to next question
iterator++;
console.log(data);
}
var data = {};
//user can click already submitted values to load that orignal question and change it/
function redo(q, id) {
q = Number(q);
//if the current queston on the page is not the one being clicked we then change it to the one being clicked
if (q + 1 != iterator) {
$('.form').load(quest[q], function () {
$('#p').val(data[id]);
});
iterator = q + 1;
};
};
$(document).ready(function(){
$('.rentanswer p').on('click',function(){
console.log('hey');
});
});

Here you go with a solution https://jsfiddle.net/g8xt5g4y/
$(document).ready(function(){
$(document).on('click','.rentanswer p',function(){
console.log($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Do you know your individual monthly rent cost?</h3>
<div class="rentanswer">
<p>Yes</p>
<p>No</p>
</div>
I believe your HTML is getting rendered dynamically, that's why your click method isn't working.
Try event delegate (mentioned in th above code).
Hope this will help you.

Related

How to detect if new element is added in DOM? [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I am trying to make a website, in which one makes a questions and there will be options for that questions.
I have a add option button, when user clicks the add option button, new option is added by this function.
function addOption(elem) {
elem = $(elem);
let ul = $(elem.parent().children()[1]);
let addedElem = $(
`<li class='ques-li'><input type='text' name='ques-option' class='ques-option' value='Option'><p class='remove-op'>X</p></li>`
);
addedElem.appendTo(ul);
}
let addOp = $('.ques-add');
$('.ques-add').click(function () {
addOption($(this));
});
This works well with one question, but when a user adds another question.
It is by this function.
let addQuestion = $('form button');
addQuestion.click(function () {
let quesBox = $('div.questions-box');
quesBox.html(quesBox.html() + `<div class='ques'>
<input type="text" name="ques-name" class="ques-name">
<ol class='ques-ul'>
<li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
<p class='remove-op'>X</p>
</li>
<li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
<p class='remove-op'>X</p>
</li>
</ol>
<p class='ques-add'>Add Another</p>
</div>`)
});
When i click the add Question button, it also works
but when i click the add option button on a newly created question,
it does not create a new option.
I noticed when i create a new question, it does not get the new option button.
So, i updated my code as follows :-
let addOp = $('.ques-add');
$(document).bind('DOMNodeInserted', function(){
addOp = $('.ques-add');
});
addOp.click(function () {
addOption($(this));
});
It also does not work.
I have no idea why this code is not working.
Thanks in advance.
Try using delegation approach that uses .on(). This will assure that the event will be attached to all the elements that are added to the document at a later time:
$('body').on('click', '.ques-add', function () {
addOption($(this));
});

Onclick Event Not Working For Idle Game [duplicate]

This question already has answers here:
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 5 years ago.
I am making an idle game and want something to be purchased on user click. I have an onclick event connected to it which triggers the buyCreateScript() function but it is not working. Any advice?
Fiddle:https://jsfiddle.net/wizviper/m1ftgoyp/82/
Javascript:
function buyCreateScript() {
if(bytes >= createScriptCost ) {
createScriptAmount++;
bytes = bytes - createScriptCost;
createScriptCost = createScriptCost * priceIncrease;
}
}
HTML:
<button type="button" class="btn-primary" id="createScript"
onclick="buyCreateScript()">Create Script-0</button>
You need to change how you load the javascript in your fiddle.
Click on the javascript options cog icon
Change "LOAD TYPE" to "No wrap - in < head>"
Click "Run" and try again
The solution is to either:
Keep the onclick attribute but add a script tag in the html section and write the function buyCreateScript() in it:
<button type="button" class="btn-primary" id="createScript" onclick="buyCreateScript()">Create Script-0</button>
<script>
function buyCreateScript() {
console.log('works');
}
</script>
Or, you could add an event listener in the javascript section, remove the onclick attribute and keep your function where it is:
var createScriptBtn = document.getElementById('createScript');
createScriptBtn.addEventListener('click', function() {
buyCreateScript();
});
function buyCreateScript() {
console.log('works');
}
<button type="button" class="btn-primary" id="createScript">Create Script-0</button>

Function Calls but element disappears

Hi I'm trying to make a simple zodiac webpage that grabs the answer from an array using a function that has a for loop and an if statement, but the answer when I click the button continues to just flash and disappear. How do I keep the answer on the page?
Here's the HTML:
<div class="header"><h1 class="zodiactitle">Learn your Life's Mysteries w/ the </br>ZODIAC</h1></div>
<form>
<input id="zodiac" placeholder=" ENTER YOUR ZODIAC">
<span class="click"><button class="button" onclick="getZodiac()">Click to find out more</button></span>
</form>
<div class="details">
<h3 id="birthdate"></h3>
<h3 id="zodiacsign"></h3>
</div>
Here's the function:
function getZodiac(){
var sign = document.getElementById("zodiac").value;
for( i = 0; i < zodiacSigns.length; i++){
//if statement to match correct input to correct zodiac
if(sign == zodiacSigns[i].sign){
document.getElementById("birthdate").innerHTML = zodiacSigns[i].birthdate;
document.getElementById("zodiacsign").innerHTML = zodiacSigns[i].zodiac;
return;
}
}
}
Hey I think the problem is that when you click the button, your form is being submitted and your page flashes. You can add Event.preventDefault() and Event.stopPropagation() to fix it. I made a demo for more clarity.
function getZodiac(e) {
e.preventDefault();
e.stopPropagation();
// the rest of your logic
}

jQuery .click() not working in search suggestion [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
i want to create search suggestion. input type is created in this way:
<div class="signup_content_3">
<div class="signup_fieldName">
<p>
title
</p>
</div>
<div class="signup_text signup_input signup_search_parent" id="signup_flavorActor">
<input type="text" class="signup_searchType">
<div class="signup_suggestion">
</div>
</div>
my jQuery function to find key up is:
$('.signup_searchType').keyup(function(event){
$.ajax({url:"http://localhost:8000/auth/search/",success:function(result){
id=event.target.id;
var parent=event.target.parentElement.parentElement;
var add=parent.getElementsByClassName('signup_suggestion')[0];
add.style.display='block';
var child=add.firstChild;
while(add.firstChild){
add.removeChild(add.firstChild);
}
for(var i=0;i<Object.keys(result).length;i++){
var div=document.createElement('div');
div.innerHTML=result[i];
div.className='signup_oneSuggestion';
add.appendChild(div);
}
}})
});
and my jQuery click function is:
$('.signup_oneSuggestion').click(function(event){
console.log('click');
});
when i type in search type search suggestions appear but when i click on them does not print anything in console.
Use .on() (jQuery 1.7) with the element's ancestor, since it is created dynamically
$('.signup_suggestion').on('click', '.signup_oneSuggestion', function(event) {
console.log('click');
});
Dynamically created elements can be assigned an event in this way
$('body').on('click', '.signup_oneSuggestion', function(event) {
console.log('click');
});

Jquery: Toggle closest parent element using .on("click")? [duplicate]

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 9 years ago.
Given HTML such as
<div class="tpl grey">Hosts:
<p>Hi !</p>
<p>How are you ?</p>
<p>What ever.</p>
An other child & element type !
</div>
How to make that a click on a child element toggle the class="grey" of the closest parent .tpl element ?
The following code fails :
//Action to do on parent $(".tpl")
var switch1 = function () {
$(this).closest(".tpl").toggleClass("blue grey");
}
// On() click event
$(document).ready(function() {
$(".tpl").on("click", "p", switch1() );
});
Fiddle: http://jsfiddle.net/MRcCy/1
If you just want to toggle the closest .tpl (even though i only see one) try this
$(document).ready(function() {
$(".tpl p").click(function(){
$(this).closest('.tpl').toggleClass('grey');
});
});
Check this fiddle
$(document).ready(function() {
$(".tpl").click(function(){
$('.tpl').toggleClass('grey blue');
});
});

Categories

Resources