Changing a dynamically created label's text with keyup() issue - javascript

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle

I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

Related

Set HTML text input to null with JQuery

Using JQuery event handlers I want to adjust the default value of a HTML text input and set it to empty.
The input
<button id="setColor">Set Color</button>
<input type="text" id="colorText">
The function
$("#setColor").on("click", function ()
{
document.getElementById('#colorText').defaultValue = "";
});
I have also tried
$("#colorText").defaultValue = "";
$("#colorText").val = "";
$("#colorText").value = "";
but every time I click the SetColor button it seems to keep its previously set default value.
document.getElementById('colorText').defaultValue = "#0000ff";
Your question is not cleared to me, But i got a simple mistake in your code, you write extra # in getElementById
try this:
$("#setColor").on("click", function ()
{
document.getElementById('colorText').value = "";
});
Are you trying to reset the textbox color or want to reset the value?
document.getElementById('colorText').value = '';
$("#colorText").val("");
You can try this with jquery.

Recursive IDs and duplicating form elements

I have the following fiddle:
http://jsfiddle.net/XpAk5/63/
The IDs increment appropriately. For the first instance. The issue is when I try to add a sport, while it duplicates, it doesn't duplicate correctly. The buttons to add are not creating themselves correctly. For instance, if I choose a sport, then fill in a position, and add another position, that's all fine (for the first instance). But when I click to add another sport, it shows 2 positions right away, and the buttons aren't duplicating correctly. I think the error is in my HTML, but not sure. Here is the JS I am using to duplicate the sport:
$('#addSport').click(function(){
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $('div.kpSports').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#kpSport').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
});
Hoping someone has an idea, perhaps I've just got my HTML elements in the wrong order? Thank you for your help! I'm hoping the fiddle is more helpful than just pasting a bunch of code here in the message.
The problem is in your clearCloneValues function. It doesn't differentiate between buttons and other for elements that you do want to clear.
Change it to:
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined && element.attr('type') !== 'button'){
element.val('');
}
}
As #PHPglue pointed out in the comments above, when new positions are added, they are incorrectly replicated (I'm assuming here) to the newly cloned for
There is a similar problem with the add years functionality.
A quick fix would be to initialize a variable with a clone of the original form fields:
var $template = $('div.kpSports').first().clone();
Then change your addSport handler to:
$('#addSport').click(function () {
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $template.clone();
…
});
However, there are no event bindings for the new buttons, so that functionality is still missing for any new set of form elements.
Demo fiddle
Using even a simple, naive string based templates the code can be simplified greatly. Linked is an untested fiddle that shows how it might be done using this approach.
Demo fiddle
The code was simplified to the following:
function getClone(idx) {
var $retVal = $(templates.sport.replace(/\{\{1\}\}/g, idx));
$retVal.find('.jsPositions').append(getItemClone(idx, 0));
$retVal.find('.advtrain').append(getTrainingClone(idx, 0));
return $retVal;
}
function getItemClone(setIdx, itemIdx) {
var retVal = itemTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, itemIdx);
return $(retVal);
}
function getTrainingClone(setIdx, trainingIdx) {
var retVal = trainingTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, trainingIdx);
return $(retVal);
}
$('#kpSportPlayed').on('click', '.jsAddPosition', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var itemIdx = $container.find('.item').length;
$container.find('.jsPositions').append(getItemClone(containerIdx, itemIdx));
});
$('#kpSportPlayed').on('click', '.jsAddTraining', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var trainIdx = $container.find('.advtrain > div').length;
$container.find('.advtrain').append(getTrainingClone(containerIdx, trainIdx));
});
$('#addSport').click(function () {
var idx = $('.kpSports').length;
var newItem = getClone(idx);
newItem.appendTo($('#kpSportPlayed'));
});

How can I create a combobox with saving value in javascript (similar to google CategoryFilter Control)

I want to have on my html-site an combobox like on the following img. I want to get the selected values and print in out. How can I create this comboBox?? I have tried the Google API Visualization CategoryFilter Control. But you can not customize the google control.
Thank you
I just mocked up a combo-box like you described: http://jsfiddle.net/twwGM/
Basically, you need to use JS to capture the onchange event of the select box, and then append its value to some target area with specific styling by generating an HTML string from your function. Keep styles out of the JS and instead style it through the use of a CSS class.
HTML Markup:
<form>
<select id="selector">
<option>Magic</option>
<option>Canaries</option>
<option>Unicorns</option>
</select>
</form>
<div id="target-area"></div>
JS Code
(function () {
document.getElementById("selector").addEventListener("change", function () {
var val = this.options[this.selectedIndex].value;
var genId = val + "-close";
if (!document.getElementById(genId)) {
var htmlstr = "<div class='pasted-option'>" + val + "<span id='" + genId + "'>x</span></div>";
var targetArea = document.getElementById("target-area");
targetArea.innerHTML += htmlstr;
var closeButton = document.getElementById(genId);
closeButton.addEventListener("click", function () {
var parent = this.parentNode;
parent.parentNode.removeChild(parent);
});
}
});
}(window));
As you can see within the code, we also generate an id for the span based on the item's name so that we can make a call to it later for removal from the list. It also gives us the ability to check and make certain the value doesn't already exist within the list.

How to remove style one click event?

How can i remove the style class applied to a textbox on the click event? I'm calling the textbox element using getElementsByName(). Here's my code:
<input id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
function clearText(element)
{
id = element.getAttribute("id");
var textElement = document.getElementById(id);
textElement.value = "";
var element = document.getElementsByName("popUpText");
var count = 0;
for (count = 0; count < 2; count++) {
var id = element.item(count);
id.classname = "";
}
}
In the above script, im not getting the id in the variable id. Right now the values are like "#inputTextBoxName". Please help.
you can use removeClass();
you can manege your styling using attr();
exp:
$("#yourid").attr("style","float: right");
or remove class using
$("#yourid").removeClass("yourClass");
It is case sensitive so
id.className = '';
If you're trying to remove the class from the textbox when you click on the textbox itself, that code is far, far longer than it needs to be.
HTML:
<input type="text" id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
Javascript:
<script>
function clearText(element) {
element.className = '';
element.value = '';
}
</script>
That said, inline event handlers (ie. declaring an onclick attribute on your HTML element) are a bad practice to get into.
Also, if you pass in a reference to an element, get its id, then call document.getElementById() with said id, you end up with two references to the same element. Yes, it should work, but totally pointless.

jQuery: Change element type from hidden to input

I've got an input which it's type is set to hidden, I need to change it's type to text. Can't seem to figure this out or if it's possible with jQuery
With jQuery 1.4 you can change the type of an input while it's detached.
marker = $('<span />').insertBefore('#myInput');
$('#myInput').detach().attr('type', 'text').insertAfter(marker);
marker.remove();
I'm not sure this is possible, so I would suggest using a hidden div to contain the input element, which can be shown as needed. The text input field can still hold data even if it's hidden.
IE won't allow you to change the type of a form element for security reasons so I would go with Aram's hidden div suggestion.
Here's how I would do this:
$("input[type='hidden']").each(function(){
var name = $(this).attr('name'); // grab name of original
var value = $(this).attr('value'); // grab value of original
/* create new visible input */
var html = '<input type="text" name="'+name+'" value="'+value+'" />';
$(this).after(html).remove(); // add new, then remove original input
});
If you want to filter some of the elements call filter() before each(), like this:
$("input[type='hidden']").filter("[name='whatever']").each(function...
easy man...
$('input[type="hidden"]').each (function() { this.type = 'text'; });
Trigger it on a event
Overlay.toAnyType = function (c, type) {
var shadow = jQuery(document.createElement(c.context.nodeName));
// Clone attributes to new object.
for (var i = 0; i < c[0].attributes.length; i++) {
var attr = c[0].attributes[i].name;
var val = c[0].attributes[i].value;
if (attr == "type") val = type;
shadow.attr(attr, val);
}
shadow.insertAfter(c);
c.remove();
};
When c is a jQuery object; the function above changes type attribute. Usage:
var inputElemt = jQuery("#input");
Overlay.toAnyType(inputElemt, "text");
Old thread, but I recently needed to do something similar but with file fields and clearing them... I think the same solution could apply, but at least you can grab the contents in this case.
var temp = $('#hidden-field').val();
$("#container-for-field").html("<input id='not-hidden' type='text' value='"+temp+"'/>");
That should also solve the problem :).

Categories

Resources