jQuery - Added Input will not allow me to add text - javascript

After I create an input it will not allow me to add text. I am working on a project that allows the user to edit their text by clicking on the added text to make a changes.
CodePen example
var $input = $("#change");
var $btn = $("#add");
var $btne = $("#edit");
var $content = $("#content");
$btne.hide();
$btn.click( function(){
var typedInfo = document.getElementById("change").value;
var item = $('<li></li>');
item.append(typedInfo);
$content.append(item);
$content.on("click","li", function(){
});
item.click( function(){
$btne.show();
item.text(" ");
var typeNew = $('<input type="text" id="newInput" value = "edit">')
item.append(typeNew);
$btne.click( function(){
var editedInput = document.getElementById("newInput").value;
item.text(editedInput);
$btne.hide();
});
});
});

As you may be know, when you click on an element, the click event is propagated to the top of the document.
So, when you click on a new input, the click is propagated to his parent <li> and the item.click(function(){...}) is called once again and the code is an other time executed and it rebuild all the current input area.
You have to stop the click event propagation to his parents.
typeNew.click( function(e){
e.stopPropagation();
});
The full code
item.click(function(){
$btne.show();
item.text(" ");
var typeNew = $('<input type="text" id="newInput" value = "edit">')
item.append(typeNew);
// Click on the new input
typeNew.click( function(e){
e.stopPropagation();
});
// Click on button
$btne.click( function(){
var editedInput = document.getElementById("newInput").value;
item.text(editedInput);
$btne.hide();
});
});
stopPropagation documentation

item.click are in loop, always you click in item a new input is created. You can check for only one click with JQuery:
$("some_selector").one("click",function);

Related

Javascript and Jquery fire function when textbox changes

How can I fire those functions when I click buttons? I need to run it when some text has change. but I have a button on my page.. when I type it changes but when I use buttons to change the value it doesnt fire the functions(codes)
$(document).ready(function(){
var text1 = $(':text'),
text2 = $(':text'),
text3 = $(':text'),
text4 = $(':text'),
activeInput = text1;
activeInput.focus();
$(':text').on('focus', function(){
activeInput = $(this);
});
$(':button').on('click', function(){
activeInput.val(activeInput.val()+ $(this).val());
$('#dec').change(function(){
fromdecimal();
})
$('#bin').bind('change click ', function(){
frombinary();
})
$('#hex').bind('change click',function(){
fromhexadecimal();
})
$('#oct').bind('change click',function(){
fromoctal();
})
});
});
are you using :(colon) to select class?? if yes then you are doing wrong.
use . (dot) to select class like
var text = $('.text');
for any other issue , show your html code.

Other elements does not listening to CustomEvent

This is simplified problem I am facing.
I have a button. When this button is clicked it will dispatch custom event customClick. So I want other DOM elements, like input, to listen for this custom events.
But input does not listen. Only button which dispatch event would listen to customClick.
What I am doing wrong? How can I make input element listen to customClick event?
var button = document.getElementById('customClick');
button.addEventListener('click', function(e){
var clickedButton = e.currentTarget;
var newEvent = new CustomEvent("customClick");
//console.log(newEvent);
clickedButton.dispatchEvent(newEvent);
})
button.addEventListener('customClick', function(e){
alert('button listening customClick');
})
var input = document.getElementById('input');
input.addEventListener('customClick', function(e){
alert('input listening customClick');
})
<button id="customClick">custom click</button>
<input id="input" type="text" />
With the setup you have, you would need to dispatchEvent to the input, with:
input.dispatchEvent(newEvent);
However, keep in mind any element on the page can be selected within the original click event listener on the button. Meaning you could select all input elements with something like `document.querySelectorAll('input'). This would eliminate the need for dispatching a secondary event.
var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customClick");
button.addEventListener('click', function(e) {
var clickedButton = e.currentTarget;
clickedButton.dispatchEvent(newEvent);
input.dispatchEvent(newEvent);
})
button.addEventListener('customClick', function(e) {
alert('button listening customClick');
})
input.addEventListener('customClick', function(e) {
alert('input listening customClick');
})
<button id="customClick">custom click</button>
<input id="input" type="text" />
A better way to handle this, possibly, would be to attach the customClick listener event to the window object instead of the specific input. Like this:
var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customButtonClick");
button.addEventListener('click', function(e) {
var clickedButton = e.currentTarget;
window.dispatchEvent(newEvent);
// Any element on the page can be accessed in here. For example,
// document.querySelectorAll('input') would select all `input`
// elements.
})
window.addEventListener('customButtonClick', function(e) {
alert('button listening customClick');
// and access the input using `document.getElementById('input')
// in here. However, you could just access the `input` within
// the original button `click` event.
})
<button id="customClick">custom click</button>
<input id="input" type="text" />

How to add an event handler to an element which is rendered on a button click?

I have two links on a page. When I click on the second link, it displays certain fields. I want to write a onkeyup() event handler for one of the fields. I have written the code like this and I'm missing something. Please help.
var inputBox;
$().ready(function() {
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function(){
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
});
//This is not working. inputBox is declared as global variable.
inputBox.onkeyup = function(){
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
}
});
Please point out my mistake. TIA :)
UPDATE:
I can get the element by ID only after clicking the cc_sec link. So I cannot do inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}"); in the beginning of the ready function.
use jQuery .on to add eventhandler to dynamically created elements.
$('body').on("keyup","{!$Component.pg.pb.cardForm.cardnumber}",function(){
alert($(this).val());
document.getElementById('printCardNo').innerHTML = $(this).val();
});
You have two options
call document.getElementById in document ready:
var inputBox;
$().ready(function() {
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function() {
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
});
inputBox.onkeyup = function() {
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
};
});
or set onkeyup in click event:
var inputBox;
$().ready(function() {
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function() {
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
inputBox.onkeyup = function() {
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
};
});
});

Duplicated button doesn't work click();

I have the code below:
$(document).ready(function(){
var counter = 0;
$("button").click(function() {
$('body').append("<button>generate new element "+(counter++)+"</button>")
});
});
JSFiddle
When you click duplicated button, it won't duplicate another button again besides the original button only works.
Why cannot listen this event to duplicated buttons?
EDITED:
//Click button event DELEGATION
$(document).on("click",".choice", function() {
var userChoice = $(this).attr("value");
//EXTERNAL SPAGUETTHI CODE
};
Need to grab "value" of this button when it's clicked.
You need delegation: catching the clicks on the parent but only those that were made on button elements. $("button") selects the existing buttons on the page, $(document) (you can replace document with your button container) will select the container and by using $(document).click("button", ...) you delegate the clicks on the buttons.
$(document).ready(function() {
var counter = 0;
$(document).click("button", function(e) {
var value = $(e.target).attr("data-value"); // or .data("value")
alert(value);
$('body').append("<button data-value=\"" + ++counter + "\">generate new element " + counter + "</button>")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-value="initial-button">generate new element</button>
Here are some other similar answers I posted:
Direct and delegated events
Delete dynamic elements
Function not working second time

Detecting href click

Ok, so I have been trying for a few days now to figure out how to detect a user click, and assign new properties to a variable. I have attempted this in a few different ways most of them however not working.
So far I have this, which is pretty self explainitory.
var settings = {
objSlideTrigger: '#one', // link button id
objSlidePanel: '#content-one' // slide div class or id
};
if(document.getElementById('#one').click) {
var setup = settings;
setup.objSlideTrigger = '#one',
setup.objSlidePanel = '#content-one'
};
if(document.getElementById('#two').click) {
var setup = settings;
setup.objSlideTrigger = '#two',
setup.objSlidePanel = '#content-two'
};
when the user clicks a href on the page it I want it to be detected by the javascript and, for the correct setup to be placed within the settings var for use by the rest of the code.
I have two questions really the first being, I will have to duplicate the conditional statement at least ten times so is there anyway to condense/simplify the code.
secondly,When detecting a Href click in javascript do i have to assign an onclick value to the actual element in the html?
thanks again.
With jQuery
Assuming you're wanting to use jQuery because you've included it at the top, use:
$(document).on('click', '#one', function( event ) {
//Do Code here
//For #one click event
});
Although, to prevent DRY - keep it more generic by using Classes:
<div class="updatesettings" id="one">One</a>
<div class="updatesettings" id="two">Two</a>
<script>
$(document).on('click', '.updatesettings', function( event ) {
//Do Code here
//For all .updatesettings click event
alert( $(this).attr('id') );
});
</script>
With JavaScript
var OnOneClick = function() {
// Your click handler
};
var OneClick = document.getElementsById("#one");
OneClick.addEventListener('click', OnOneClick, false);
Then to listen for multiple, use by Class (Although not all IE versions can listen for this):
var AwaitedClickEvent = function() {
//Class Click
}
var WaitingClick = document.getElementsByClassName('clickme');
for (var i = 0; i < WaitingClick.length; i++) {
var current = WaitingClick[i];
current.addEventListener('click', AwaitedClickEvent, false);
}
Your Solution
<!-- Links with ID & Content -->
<div class="updatesettings" id="one" data-content="content-one">One</a>
<div class="updatesettings" id="two" data-content="content-two">Two</a>
<script>
/**
* Get the clicked element's ID
* and it's stored data-content string.
**/
$('.updatesettings').on('click', function( event ) {
var Id = $(this).attr('id'),
Content = $(this).data('content'),
setup = settings,
setup.objSlideTrigger = Id,
setup.objSlidePenl = Content;
console.log( setup );
});
</script>

Categories

Resources