referencing jQuery created element, to register a click (with fiddle) - javascript

I'm working on a project which would require the user to be able to add, and edit tags.
On the page, is: a div container, containing the tags, a textbox (newTag) and a button (add tag) that will add a tag to the container. Another textbox (editTag) and a button (update tag) that will update the tag information typed in by the user. There is also a select list that will, in realtime - keep track of all the changes made.
Wen a user clicks on a tag that was already rendered, to edit it - all works well. The tag name goes into the edit textbox, and the tag is selected in the list.
The problem arises when a user created tag gets clicked... nothing happens. I have a feeling it has to do with the fact the object is in the DOM, but isn't rendered HTML. But I have no clue as to how to resolve this issue - how to reference a click of a dom object.
Here's my code:
HTML:
<!-- tags container -->
<div class="container_12">
<div class="grid_2"><img src="images/spacer.png" /></div>
<div id="content" class="grid_8">
<button name="PHP" class="tag-button">PHP</button>
<button name="CSS" class="tag-button">CSS</button>
</div>
<div class="grid_2"><img src="images/spacer.png" /></div>
</div>
<!-- tags container end -->
<!-- action buttons container -->
<div class="container_12 action-bar">
<div class="grid_4"><img src="images/spacer.png" /></div>
<div id="action-add">
<input type="text" name="newTag" id="newTag" />
<input type="button" id="add" value="Add tag" />
</div>
<div class="grid_4"><img src="images/spacer.png" /></div>
<div id="action-edit">
<input type="text" name="editTag" id="editTag" />
<input type="button" id="update" value="Update tag" />
</div>
<!-- action buttons container end -->
</div>
<!-- Real Time list container -->
<div class="container_12">
<div class="grid_4"><img src="images/spacer.png" /></div>
<select id="insertString">
<option value="0">PHP</option>
<option value="1">CSS</option>
</select>
</div>
<!-- real time list container end -->
jQuery:
//button add click
$('#add').click(function() {
//creating a new tag for the tag bar
var tag = $('#newTag').val();
var tagHTML=$('<button name= "' + tag + '" class="tag-button">'+ tag + '</button>');
var qString = "";
// adding the tag to the bar
$("#content").append(tagHTML);
//get last value in the list
var lastValue = $('#insertString option:last-child').val();
if (! lastValue) {lastValue = 0;}
else {lastValue = ++ lastValue; }
//add new option for the new tag
$('<option value="' + lastValue + '">' + tag + '</option>').appendTo("#insertString")
})
//tag button click
$(".tag-button").click(function(){
var name = $(this).attr('name');
//add the tag name to the editTag textbox
$('#editTag').val(name);
$('#insertString option:contains("'+ name + '")').attr('selected', true);
});
Also, here's my fiddle:
http://jsfiddle.net/Lm3ab/
Help would be appreciate, and thank you for your time.

You need to use Event Delegation. You have to use .on() using delegated-events approach.
Use
$("#content").on("click", ".tag-button", function() {
DEMO

just add another click, thus
$("#content").on("click", ".tag-button", function(){});
http://jsfiddle.net/Lm3ab/1/

Event delegation, since these tags weren't on the page at the time of the click events being binded, they have no listeners. Bind the click event to the container and target the elements:
$("#content").on("click", ".tag-button", function() {

Related

Button Onclick only working on first element

When clicking button on elements, overlay box only works with first one, not the rest
I tried already to add 2 classes but not working as I read that that might be the issue, but I am not able to make it work properly.
<div class="container">
<input type="button" value="Contactar ahora" id="Overly" class="overly"
/>
</div>
<div id="ogrooModel" class="modalbox ogroobox" >
<div class="dialog">
<button title="Close" onClick="overlay()" class="closebutton" id="close">close</button>
<div style="min-height: 150px;">
</div>
</div>
</div>
<script>
//only javascript
document.getElementById("Overly").addEventListener("click", function(){
var e =document.getElementsByClassName("modalbox");
e[0].style.display = 'block';
}) ;
document.getElementById("close").addEventListener("click", function(){
var e =document.getElementsByClassName("modalbox");
e[0].style.display= 'none';
});
</script>
What exactly to change in that code so the rest of elements display the box after clicking on button?
You don't need onClick="overlay()" for your close button, as you are already binding it with a click event listener in your script.

Hw do I clck the add btn and it display the info in the input field and display it n a <p> created with JS. (no inline JS)

Im trying to take the user input and add it to the page with the click of the button and add it to the page in a new paragraph element created thru javascript, I didn't want to use any inline javascript and I wanted to use as little html as possible and do it mainly thru javascript.
<body>
<div class="input">
<form>
<input id="input" type="text" placeholder="Enter task to do..." />
<button id="add_btn">Add</button>
</form>
</div>
<div class="task_list">
<ul id="todo">
<li></li>
</ul>
</div>
<script>
//take user input and add it to the page as a task to do
let div = document.querySelector('.task_list');
let input = document.querySelector('#input')
let pElement = document.createElement('p');
let add = document.getElementById('add_btn');
div.appendChild(pElement);
add.addEventListener(onclick, function (){
input.value;
pElement.innerHTML = input;
console.log(add);
});
</script>
You've got some problems with your code:
You're wrongly binding the event listener. You should use 'click' instead of onclick (which isn't defined anyway).
You didn't define any button type, so the button is treated as submit button, by default. Add type="button" attribute so that the page doesn't refresh on clicking on it.
In the event listener, you should create a fresh p element always, and assign its textContent with input.value (unless you're dealing with HTML content, in which case, innerHTML would be appropriate).
The following snippet makes the code work. Not sure what end result should be like (e.g. you may want to append the list items in ul), but this can get you on track.
//take user input and add it to the page as a task to do
let div = document.querySelector('.task_list');
let input = document.querySelector('#input')
let add = document.getElementById('add_btn');
add.addEventListener('click', function() {
let pElement = document.createElement('p');
pElement.textContent = input.value;
div.appendChild(pElement);
});
<div class="input">
<form>
<input id="input" type="text" placeholder="Enter task to do...">
<button type="button" id="add_btn">Add</button>
</form>
</div>
<div class="task_list">
<ul id="todo">
<li></li>
</ul>
</div>

Why button will not append text from textarea to a panel (Bootstrap)?

I am trying to trigger an event with a button that takes text from a textarea and sends it to a panel using the Bootstrap Framework (v.3.3.7). Currently trying to do this using an event listener in Javascript rather than assigning an ‘onclick’ value for the button.
HTML:
<div class="container-fluid">
<div class="row">
<!-- Panel where text will be appended to -->
<div id="mainChatBox" class="panel-body" style="height:435px; overflow-y:scroll"></div>
<!-- Textarea and button -->
<div class="panel panel-footer" style="height:40px">
<div class="form-group col-md-10 col-lg-10">
<input type="text" placeholder="Type your message here" class="form-control" id="messageBar" />
</div>
<div class="input-group-btn col-md-2 col-lg-2">
<button id="sendMessageButton" class="btn btn-default">Send</button>
</div>
</div>
</div>
</div>
Javascript
var sendMessageButton = document.querySelector('#sendMessageButton');
var messageBar = document.querySelector('#messageBar');
var mainChatBox = document.querySelector('#mainChatBox');
sendMessageButton.addEventListener("click", function (event) {
var message = messageBar.value;
mainChatBox.innerHTML += message + "<br />";
});
I tried debugging by using this code and another version where I instead assign the button an ‘onclick’ value and then keep the function for it.
Here is a link to a reddit post with that version of code where I tried to find a solution with assigning an ‘onclick’ value to the button instead of using an EventListener.
Reddit post link
I need to know why when the event is triggered by the button that the text will not be appended to the mainChatBox when using either the method with the 'onclick' value assignation to the "button" tag for sendMessageButton, or the EventListener in the Javascript.

Making div contents persistant

I have an interesting problem, which I would like some help with if possible.
I have the following segments of HTML:
<div id="main_">
<ul class="unstyled">
<ui:repeat var="adultPassenger" varStatus="adult" value="#{bean.adultPassengers}">
<li>
<div id="adult#{adult.index}" class="hitbox_">
<div id="passengerTitle">Adult #{passengerDetailsBean.getPassengerCount(adult.index)}</div>
</div>
<div class="hide">
<div id="adult#{adult.index}_form">
<div>
<div>
<div class="pull-left" style="width: 50%;">
<div><h:inputText value="#{adultPassenger.firstName}" class="pasFirstName_adult#{adult.index}" label="First Name"></h:inputText></div>
</div>
<div class="button-container">
<h:commandButton value="Continue" styleClass="btn btn-warning btn-large btn-block" onclick="handleDetailsClick('adult#{adult.index}')"></h:commandButton>
</div>
</div>
</div>
</div>
</div>
</li>
</ui:repeat>
</ul>
</div>
and
<div id="secondary_" class="hide">
<table>
<tbody>
<tr>
<td">
<h:commandButton id="secondaryBack" value="Back" styleClass="btn btn-warning">
</h:commandButton>
</td>
<td class="secondaryTitle">
<h3 class="page-title orange-title-big">Passenger Details</h3>
</td>
</tr>
</tbody>
</table>
<div id="secondaryContents">
</div>
</div>
They're both on the same page, and when the one div is visible the other is invisible. Thing is. Here's the JS I'm currently using:
$(".hitbox_").click(function() {
var round = Math.round;
var id = $(this).attr("id");
window.alert(id);
var f = $("pasFirstName_"+id).get();
console.log("name " + f.value);
// set contents of secondary div
var passengerDetails = $("#" + id + "_form").html();
$("#secondaryContents").html(passengerDetails);
$("#main_").toggleClass("hide");
$("#secondary_").toggleClass("hide");
});
function handleDetailsClick(index) {
var passengerDetails = $("#" + index + "_form").html();
$("#secondaryContents").html(passengerDetails);
$("#main_").toggleClass("hide");
$("#secondary_").toggleClass("hide");
}
What I want(and have tried, unsuccessfully, to achieve):
When the first div is clicked, it is hidden and the second div is shown after being populated with the hidden form in the first div. I do this to preserve class names etc, since there could be more than one such form.
When "Continue" is clicked, the second div is hidden, and it's contents passed back to the first div - I do this to preserve the details that were entered on the form.
My problem is that the details don't persist. When the same div is clicked again after having filled in the form before, it should should the form with the details that were previously entered.
This is where something goes wrong because there are never details in the form.
Does anyone know what I could be doing wrong?
The problem is in the following lines
var passengerDetails = $("#" + id + "_form").html();
$("#secondaryContents").html(passengerDetails);
Here, you are taking HTML of one div and adding it to another. While this will surely create the same html in target div, it will not retain any user entered values as well as any events bound on elements.
You should, instead, take the element and append it to target
var passengerDetails = $("#" + id + "_form").children();
$("#secondaryContents").append(passengerDetails);

if jQuery element hasClass() change different element link text

I am using a jQuery function to add/remove a class to the clicked element, which works just fine. However when that element is clicked, I am trying to change the text of an HTML link and I cannot seem to get it working. The HTML link is located within the <span> element further down the page.
When <button id="people"> hasClass('user_view_active') the HTML link should display "People" when <button id="jobs"> hasClass('user_view_active') the HTML link should display "Jobs".
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function(){
$('button').each(function(){
$(this).removeClass('user_view_active');
});
$(this).addClass('user_view_active');
});
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").attr("href").text(text.replace('People'));
}else{
$('.title').find("a").attr("href").text(text.replace('Jobs'));
}
});
</script>
</head>
<body>
<div id="container">
<header>
<img src="images/header-name.png" width="200px" style="display: inline; margin-bottom: -10px;"/>
<button id="jobs" class="user_view">Jobs</button>
<button id="people" class="user_view_active user_view">People</button>
<div class="header_search_wrapper">
<form action="" method="POST">
<textarea class="header_search" name="app_search" placeholder="Search people, jobs, or companies" style="width: 430px;"></textarea>
<input type="submit" class="share_btn" value="Search">
</form>
</div>
</header>
<div id="main" role="main">
<!--! begin app content -->
<div class="right_sidebar">
<span class="right_title">Connection Suggestions</title>
</div>
<span class="title">Recent Updates >> People</span>
To replace the text within a link you can use the jQuery .text() function. This function can also get the text value and also set the text value - as is shown in the example below -
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").text('People');
}else{
$('.title').find("a").text('Jobs');
}
This code would have to be wrapped in the callback function of the click event to work -
$(document).ready(function() {
$('button').click(function(){
$('button').removeClass('user_view_active');
$(this).addClass('user_view_active');
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").text('People');
}else{
$('.title').find("a").text('Jobs');
}
});
});
Now each time the button is clicked, you can check for the existence of the user_view_active class on the #people element.
Okeydokey ?
Are you sure those are the right tags ?
<span class="right_title">Connection Suggestions</title>
Are you sure an <a> element inside a <button> element is a good idea?
<button id="jobs" class="user_view">Jobs</button>
role="main" is'nt a valid attribute, but will probably work anyway.
This just seems easier:
$(document).ready(function() {
$('button').on('click', function(){
$('button').removeClass('user_view_active');;
$(this).addClass('user_view_active');
$("a", ".title").text(this.id);
});
});
FIDDLE
Try this way:
$('#people').toggleClass('user_view_active').html($('#people').hasClass('user_view_active')?'People':'Jobs');

Categories