Reputation: 77
So I have this script which is works in all aspects file apart from the targeting when I need to change the label. The Idea is you add an html tag element and then edit its settings. The console.log is returning the label value but there is a problem with the targeting its not changing the HTML of the label. Any ideas?
var tCheckbox = "<?php echo $tCheckbox ?>";
var tText = "<?php echo $tText ?>";
var tNumber = "<?php echo $tNumber ?>";
count = 0;
function addField(template) {
count++;
currentTemplate = "";
currentTemplate = template;
// ADD Databin Field -------------------------------------------
// replace all & with the designated count no
currentTemplate = currentTemplate.replace(/\&/g, count);
// add template to fieldrange
$(".field-range").append(currentTemplate);
// BIND Databin HTML Settings ----------------------------------
$(".field-set-label"+count).change(function(){
console.log("changed label")
$(this).parents(".databin-field .field-label").html($(this).val());
});
$(".delete-field" + count).click(function(){
$(this).parents(".databin-field").remove();
});
};
$("#addCheckbox").click(function(){
addField(tCheckbox);
});
$("#addText").click(function(){
addField(tText);
});
$("#addNumber").click(function(){
addField(tNumber);
});
Upvotes: 0
Views: 50
Reputation: 880
Change
$(this).parents(".databin-field .field-label").html($(this).val());
To
$(this).closest(".databin-field").find(".field-label").html($(this).val());
You did not show HTML, but I am assuming that .field-label is inside of .databin-field, which is a parent to both your .field-set-label and the label you want to change.
EDIT optmized code to use .closest rather than .parents().first(). Thanks to the answer below I've noticed that .closest offers superior performance because it stops once it finds the first element
Upvotes: 1
Reputation: 19288
If count
is used for nothing other than the element identification we see in the question, then count
is unnecessary. Event handling can be delegated to a static container element, avoiding the need to rediscover freshly appended elements.
And with the events delegated, addField()
would simplify so much it could be dispensed with.
var tCheckbox = "<?php echo $tCheckbox ?>";
var tText = "<?php echo $tText ?>";
var tNumber = "<?php echo $tNumber ?>";
$("#addCheckbox").click(function(){
$(".field-range").append(tCheckbox);
});
$("#addText").click(function(){
$(".field-range").append(tText);
});
$("#addNumber").click(function(){
$(".field-range").append(tNumber);
});
// Delegate Databin event handling to container element -----
$(".field-range").on('change', ".field-set-label", function() {// <<<< delegate to static element(s)
$(this).closest(".databin-field").find(".field-label").html($(this).val());//same assumption here as Zoran P's
}).on('click', ".delete-field", function() {// <<<< delegate to static element(s)
$(this).closest(".databin-field").remove();
});
Upvotes: 1