Holding Down Backspace not Triggering Keyup - javascript

I'm trying to write text from an input to a div on keyup with javascript and jquery by checking if the current value of the input is the same as the previous value of the input. This works fine except when you hold down the backspace key until all of the text is gone from the input. In this case it doesn't update the variables that I'm using for some reason. This happens in all browsers and only if all of the text is deleted, also only if the backspace key is used (instead of another key)
I'm pretty new at javascript so any tips are appreciated :)
javascript:
fsa = (function() {
var inputId = "";
var sigId = "";
function resetOnFocus() {
inputId = document.activeElement.id;
sigId = "sig-" + document.activeElement.id;
}
function getText() {
lastentry = $("#" + inputId).val();
}
function writeText() {
if ($("#" + inputId).val() != lastentry) {
document.getElementById(sigId).innerHTML = 'current entry :' + $("#" + inputId).val() + '</br>last entry: ' + lastentry;
}
}
return {
resetOnFocus: resetOnFocus,
getText: getText,
writeText: writeText
}
})();
//call the functions
//clear variables on focus
$('input').focus(function() {
fsa.resetOnFocus();
});
//get input value on key press
$('input').keydown(function() {
fsa.getText();
});
//prints input value on keyup if input value is new
$('input').keyup(function() {
fsa.writeText();
});
and html:
<input id="first-name" class="i1" />
<div id="sig-first-name" class="o1" /></div>
<input id="last-name" class="i2" />
<div id="sig-last-name" class="o2" /></div>

Related

How to add a function to an appended element

I have an input-text. If you type something, the text appears below (see code snippet).
Now, I need to do the same with a previous step: clicking a button (preferably a checkbox) to append/remove all. Here is my failed idea: DEMO (it appends the input text, but when you type, text won't apear below like it does on my code snippet).
I feel like the function to add text below does not work because there is a problem with selecting the appended element. How do I do this?
Any more simple idea to do this would be great
var name1 = document.getElementById('name');
name1.addEventListener('input', function() {
var result = document.querySelector('.X');
console.log(this.value );
result.innerHTML = this.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>What is your name? </label><input type="text" id="name">
<p>Your name is: <span class="X"></span></p>
Put your first part of the snippet into appending logic while clicking the add button. As in your codes, the input box is appended to the document after its listener being attached.
if (!added) {
$content = $(NewContent).appendTo('.firstappend');
// attach listener after input box actually exists!
var name1 = document.getElementById('A');
name1.addEventListener('input', function() {
var result = document.querySelector('span.Y');
console.log(this.value );
result.innerHTML = this.value;
});
}
$(function() {
let NewContent = '<div class="added">' +
'<p>' +
'<label>What is your name? </label>' +
'<input type="text" id="A">' +
'</p>' +
'<p>Your name is: <span class="Y"></span></p>' +
'</div>';
$(".addremove").on('click', function() {
if ($(".added").length) {
$(".added").remove();
} else {
$(".firstappend").append(NewContent);
}
});
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toadd">
<button type="button" class="addremove">Do you have a name?</button>
</div>
<div class="firstappend"></div>
as from the DEMO you included,
appended elements to document cannot be invoked explicitly, since you're using jQuery, you can do this
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});

Not able to attach event handler to dynamically added input fields using jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I'm trying to dynamically add input fields based on an input field value. After adding fields, I want to add events on these dynamically added input fields, and this's what I did, but I'm not getting the result I want. Here's what I tried using jquery.
html file :
<input class='cls1' id='num' />
<div id="samp"></div>
script file
function add() {
var num = $("#num").val()
data = ""
for (i = 0; i<num; i++) {
var id_name = "input_" + i
data += "<input class='cls2' id='" + id_name + "' /><br>"
}
$("#samp").show().html(data)
}
$(".cls1").on("change keyup paste", function (event) {
console.log("chng1")
// this's logging
add() // this adds input fields
})
$(".cls2").on("change keyup paste", function (event) {
console.log("chng2") // not logging
})
$("input[id^='input_']").on("change keyup paste", function (event) {
console.log("chng2") // not logging
})
Any help would be appreciated.
Try this way :
function add() {
var num = $("#num").val()
data = ""
for (i = 0; i<num; i++) {
var id_name = "input_" + i
data += "<input class='cls2' id='" + id_name + "' /><br>"
}
$("#samp").show().html(data)
}
$(".cls1").on("change keyup paste", function (event) {
// this's logging
add() // this adds input fields
})
$("#samp").on("change keyup paste",'.cls2', function (event) {
console.log("chng2") // not logging
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='cls1' id='num' />
<div id="samp"></div>

How do i rearrange the number in java script loop?

I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful

Add/Remove value to input on click

i have this code that i use, and on click i put email in field, but what i want to accomplish is that on next click on same field it removes email if one already exist in input.
Here is my code:
<p class="email">mail1#gmail.com</p>
<p class="email">something#gmail.com</p>
<p class="email">third#gmail.com</p>
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" />
And js:
var $contact = $('#contact-email');
$('.email').on('click', function () {
if ($contact.val()) {
$contact.val($contact.val() +'; '+ $(this).text());
} else {
$contact.val($(this).text());
}
});
and fiddle https://jsfiddle.net/2dffwew5/2/
I would store selected email addresses to an array. Then push or splice the clicked email.
var $contact = $('#contact-email');
var emails = [];
$('.email').on('click', function () {
var index = emails.indexOf($(this).text());
if (index > -1) {
emails.splice(index, 1);
} else {
emails.push($(this).text());
}
$contact.val(emails.join(";"));
});
https://jsfiddle.net/jdgiotta/ze7zebzq/
I would suggest that you add a check to see if the current text contains the selected email address. If it does, then remove it. Otherwise add it.
You will also need to cater for leading/trailing dividers, which can easily be done with a couple of conditional checks.
Something like this:
var $contact = $('#contact-email');
$('.email').on('click', function () {
var text = $(this).text(); // Get the value to insert/remove.
var current = $contact.val(); // Get the current data.
// Check if the value already exists with leading seperator, if so remove it.
if (current.indexOf('; ' + text) > -1) {
$contact.val(current.replace('; ' + text, ''));
}
// Check if the value already exists with trainling seperator, if so remove it.
else if (current.indexOf(text + '; ') > -1) {
$contact.val(current.replace(text + '; ', ''));
}
// Check if the value already exists with no seperator (on it's own), if so remove it.
else if (current.indexOf(text) > -1) {
$contact.val(current.replace(text, ''));
}
// Otheriwse, it doesn't exist so add it.
else {
if (current) {
$contact.val(current + '; ' + text);
} else {
$contact.val(text);
}
}
});
Here is a working example

How do you dynamically create a radio button in Javascript that works in all browsers?

Dynamically creating a radio button using eg
var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
works in Firefox but not in IE. Why not?
Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch:
function createRadioElement(name, checked) {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
Based on this post and its comments:
http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html
the following works. Apparently the problem is that you can't dynamically set the name property in IE. I also found that you can't dynamically set the checked attribute either.
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;
}
Here's an example of more general solution which detects IE up front and handles other attributes IE also has problems with, extracted from DOMBuilder:
var createElement = (function()
{
// Detect IE using conditional compilation
if (/*#cc_on #*//*#if (#_win32)!/*#end #*/false)
{
// Translations for attribute names which IE would otherwise choke on
var attrTranslations =
{
"class": "className",
"for": "htmlFor"
};
var setAttribute = function(element, attr, value)
{
if (attrTranslations.hasOwnProperty(attr))
{
element[attrTranslations[attr]] = value;
}
else if (attr == "style")
{
element.style.cssText = value;
}
else
{
element.setAttribute(attr, value);
}
};
return function(tagName, attributes)
{
attributes = attributes || {};
// See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
if (attributes.hasOwnProperty("name") ||
attributes.hasOwnProperty("checked") ||
attributes.hasOwnProperty("multiple"))
{
var tagParts = ["<" + tagName];
if (attributes.hasOwnProperty("name"))
{
tagParts[tagParts.length] =
' name="' + attributes.name + '"';
delete attributes.name;
}
if (attributes.hasOwnProperty("checked") &&
"" + attributes.checked == "true")
{
tagParts[tagParts.length] = " checked";
delete attributes.checked;
}
if (attributes.hasOwnProperty("multiple") &&
"" + attributes.multiple == "true")
{
tagParts[tagParts.length] = " multiple";
delete attributes.multiple;
}
tagParts[tagParts.length] = ">";
var element =
document.createElement(tagParts.join(""));
}
else
{
var element = document.createElement(tagName);
}
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
setAttribute(element, attr, attributes[attr]);
}
}
return element;
};
}
// All other browsers
else
{
return function(tagName, attributes)
{
attributes = attributes || {};
var element = document.createElement(tagName);
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
element.setAttribute(attr, attributes[attr]);
}
}
return element;
};
}
})();
// Usage
var rb = createElement("input", {type: "radio", checked: true});
The full DOMBuilder version also handles event listener registration and specification of child nodes.
Personally I wouldn't create nodes myself. As you've noticed there are just too many browser specific problems. Normally I use Builder.node from script.aculo.us. Using this your code would become something like this:
Builder.node('input', {type: 'radio', name: name})
My solution:
html
head
script(type='text/javascript')
function createRadioButton()
{
var newRadioButton
= document.createElement(input(type='radio',name='radio',value='1st'));
document.body.insertBefore(newRadioButton);
}
body
input(type='button',onclick='createRadioButton();',value='Create Radio Button')
Dynamically created radio button in javascript:
<%# Page Language=”C#” AutoEventWireup=”true” CodeBehind=”RadioDemo.aspx.cs” Inherits=”JavascriptTutorial.RadioDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
<script type=”text/javascript”>
/* Getting Id of Div in which radio button will be add*/
var containerDivClientId = “<%= containerDiv.ClientID %>”;
/*variable count uses for define unique Ids of radio buttons and group name*/
var count = 100;
/*This function call by button OnClientClick event and uses for create radio buttons*/
function dynamicRadioButton()
{
/* create a radio button */
var radioYes = document.createElement(“input”);
radioYes.setAttribute(“type”, “radio”);
/*Set id of new created radio button*/
radioYes.setAttribute(“id”, “radioYes” + count);
/*set unique group name for pair of Yes / No */
radioYes.setAttribute(“name”, “Boolean” + count);
/*creating label for Text to Radio button*/
var lblYes = document.createElement(“lable”);
/*create text node for label Text which display for Radio button*/
var textYes = document.createTextNode(“Yes”);
/*add text to new create lable*/
lblYes.appendChild(textYes);
/*add radio button to Div*/
containerDiv.appendChild(radioYes);
/*add label text for radio button to Div*/
containerDiv.appendChild(lblYes);
/*add space between two radio buttons*/
var space = document.createElement(“span”);
space.setAttribute(“innerHTML”, “ &nbsp”);
containerDiv.appendChild(space);
var radioNo = document.createElement(“input”);
radioNo.setAttribute(“type”, “radio”);
radioNo.setAttribute(“id”, “radioNo” + count);
radioNo.setAttribute(“name”, “Boolean” + count);
var lblNo = document.createElement(“label”);
lblNo.innerHTML = “No”;
containerDiv.appendChild(radioNo);
containerDiv.appendChild(lblNo);
/*add new line for new pair of radio buttons*/
var spaceBr= document.createElement(“br”);
containerDiv.appendChild(spaceBr);
count++;
return false;
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Button ID=”btnCreate” runat=”server” Text=”Click Me” OnClientClick=”return dynamicRadioButton();” />
<div id=”containerDiv” runat=”server”></div>
</div>
</form>
</body>
</html>
(source)
for(i=0;i<=10;i++){
var selecttag1=document.createElement("input");
selecttag1.setAttribute("type", "radio");
selecttag1.setAttribute("name", "irrSelectNo"+i);
selecttag1.setAttribute("value", "N");
selecttag1.setAttribute("id","irrSelectNo"+i);
var lbl1 = document.createElement("label");
lbl1.innerHTML = "YES";
cell3Div.appendChild(lbl);
cell3Div.appendChild(selecttag1);
}
Quick reply to an older post:
The post above by Roundcrisis is fine, IF AND ONLY IF, you know the number of radio/checkbox controls that will be used before-hand. In some situations, addressed by this topic of 'dynamically creating radio buttons', the number of controls that will be needed by the user is not known. Further, I do not recommend 'skipping' the 'try-catch' error trapping, as this allows for ease of catching future browser implementations which may not comply with the current standards. Of these solutions, I recommend using the solution proposed by Patrick Wilkes in his reply to his own question.
This is repeated here in an effort to avoid confusion:
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;}
Patrick's answer works, or you can set the "defaultChecked" attribute too (this will work in IE for radio or checkbox elements, and won't cause errors in other browsers.
PS Full list of attributes you can't set in IE is listed here:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
why not creating the input, set the style to dispaly: none and then change the display when necesary
this way you can also probably handle users whitout js better.
My suggestion is not to use document.Create(). Better solution is to construct actual HTML of future control and then assign it like innerHTML to some placeholder - it allows browser to render it itself which is much faster than any JS DOM manipulations.
Cheers.

Categories

Resources