Hide a dynamic appended div with jQuery / hide don't work - javascript

I´m trying to hide a appended div with jQuery using hide() but is not working.
I'm append the button who trigger the action too.
This is the button:
<button type="button" class="btn btn-danger btn-xs" name="'+response[i][0]+'" id="studentContactDeleteButton" style="width:110px">Eliminar registro</button>
Here is the complete code of the function (including the div and the button):
With this I append divs to my page depending of the number of my records.
var formData = {type:"contact",id:id};
$.ajax({
type: "POST",
data : formData,
url: "./content/studentsData.php",
dataType: 'json',
success: function(response){
for(var i = 0; i < response.length; i++) {
$("#contactData").append('<div id="studentContactContainer'+response[i][0]+'" style="margin-bottom:-12px;border-top:1px solid #ddd;padding:16px 0px;">');
$("#contactData").append('<div class="form-group"><label class="col-sm-4 control-label">Descripción:</label><div class="col-sm-7 text-primary" id="div-studentContactDesc'+response[i][0]+'"><input type="text" style="font-size:12px" class="form-control" value="'+decodeHtml(response[i][1])+'" id="studentContactDesc'+response[i][0]+'" placeholder="Descripción"></div><div class="col-sm-1"> </div></div>');
$("#contactData").append('<div class="form-group"><label class="col-sm-4 control-label">Teléfono:</label><div class="col-sm-7 text-primary" id="div-studentContactPhone'+response[i][0]+'"><input type="text" style="font-size:12px" class="form-control" value="'+decodeHtml(response[i][2])+'" id="studentContactPhone'+response[i][0]+'" placeholder="Teléfono"></div><div class="col-sm-1"> </div></div>');
$("#contactData").append('<div class="form-group"><div class="col-sm-1"> </div><div class="col-sm-3 text-primary"><button type="button" class="btn btn-success btn-xs" name="'+response[i][0]+'" id="button-test" style="width:110px">Guardar cambios</button></div><div class="col-sm-3 text-primary"><button type="button" class="btn btn-danger btn-xs" name="'+response[i][0]+'" id="studentContactDeleteButton" style="width:110px">Eliminar registro</button></div><div class="col-sm-3 text-primary"><button type="button" class="btn btn-primary btn-xs" id="" style="width:110px">Restablecer</button></div><div class="col-sm-2"> </div></div>');
$("#contactData").append('</div>');
}
}
});
And with this I´m trying to hide the div but is not working
$(document).on('click','#studentContactDeleteButton',function(){
var id = $(this).attr("name");
$("#studentContactContainer"+id).hide();
});
The click works fine because im getting the value of the id (response[i][0] have the value of the id) but $("#studentContactContainer"+id).hide(); is not working, only hide the border top of the div but not all.
Hope somebody have an idea.
Thanks.

You are using .append function in a wrong way. You have to pass a complete div as parameter and not in different parts.
$("#contactData").append('<div id="studentContactContainer'+response[i][0]+'"></div>');
and after add all groups to your new contactContainer like this:
$("#studentContactContainer"+id).append(<div class="form-group"></div>)
.append(<div class="form-group"></div>);
.append(<div class="form-group"></div>);

Your first append statement in your loop is appending the container, but the subsequent append statements are not appending the specified divs to the new container.
I think you want something more like this
$('<div id="studentContactContainer'+response[i][0]+'"/>')
.appendTo('#contactData')
.append('<div>child div 1</div>')
.append('<div>child div 2</div>');
For better performance, compose the entire html string before appending it, like this
var html = '<div id="studentContactContainer'+response[i][0]+'"><div>child 1</div><div>child 2</div></div>';
$('#contactData').append(html);
For easier maintainability, you may want to consider a template engine like Handlebars.

Related

Get id of elements where the ids are dynamically generated

I have a set of elements that have been generated dynamically through Handlebars as seen below
{{#floor as |room i|}}
<div class="btn-group-toggle" data-toggle="buttons" >
<label class="btn btn-secondary" id="{{id}}">
<input type="checkbox" autocomplete="off"> {{name}}
</label>
</div>
{{/floor}}
As you can see, the elements are created with id="{{id}}". But when the page finishes loading, I want to hide these elements until a user clicks a button. I'm finding it hard to get the dynamic ids
Currently, I'm using JQuery as seen below
$(document).ready(function () {
$('#{{id}}').hide();
});
this works with known ids, but not in this case where I don't know the id
If you are trying to hide the element you can also select a unique class.
{#floor as |room i|}}
<div class="btn-group-toggle" data-toggle="buttons" >
<label class="btn btn-secondary unique-class" id="{{id}}">
<input type="checkbox" autocomplete="off"> {{name}}
</label>
</div>
{{/floor}}
Using JQuery:
$(document).ready(function () {
$('.unique-class').hide();
});

Adding dynamic form elements jQuery

I am attempting to use jQuery to add the dynamic form elements to my page. At the moment I can get one of my form elements to be added when the user clicks the button but the second element isn't being added alongside it.
I do this by appending some html to divs with a specific class when a button is clicked.
I have created a JSfiddle. As you can see the 'ingredient' part is working, however the quantities is not.
https://jsfiddle.net/fe0t3by2/
$('.recipe-ingredients #addNewIngredient').on('click', function () {
var i = $('.recipe-ingredients .ingredient').size() + 1;
$('<div class="form-group ingredient"><label class="control-label" for="searchinput">Ingredients</label><div><input id="ingredient_' + i + '" name="ingredients[]" type="text" placeholder="Ingredients" class="form-control input-md"></div></div>Add Ingredient</div>').appendTo($('.recipe-ingredients .ingredients'));
$('<div class="form-group"><label class="control-label" for="buttondropdown">Quantity</label><div class="input-group"><input id="quantity_' + i + '" name="quantity[]" class="form-control" placeholder="Quantity" type="text"><div class="input-group-btn"><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Measure<span class="caret"></span></button><ul class="dropdown pull-right"><li>Grams</li><li>Ounces</li><li>Option three</li></ul></div></div>').appendTo($('.recipe-quantities .quantities'));
});
Thank you
You have misspelled the 'recipe-quantities' class on your quantities div.
<div class="col-md-6 recipe-quantites">
changed to
<div class="col-md-6 recipe-quantities">
At the moment I can get one of my form elements to be added when the user clicks the button but the second element isn't being added alongside it.
With dynamically added content you should delegate the click to the document for example (something where the object is contained in).
jQuery documentation .on()
$(document).on('click', '.recipe-ingredients #addNewIngredient', function () {
JSFiddle demo

Add html elements based on number of JSON keys

I am working on a piece of code in which I want to generate span and textarea elements based on the number of JSON key:value pairs.
This is my html:
<div class="modal fade" id="addPropertyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Property</h4>
</div>
<div class="modal-body">
<div class="input-group input-group-lg">
<span class="input-group-addon">Name</span>
<input type="text" id="newProperty" name="newProperty" class="form-control" placeholder="name">
</div>
<br/>
**<div class="input-group input-group-lg">
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
</div>**
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="savePropertyBtn" name="action" value="Save Property" class="btn btn-primary"/>
<input type="submit" id="updatePropertyBtn" name="action" value="Update Property" class="btn btn-primary"/>
</div>
</div>
</div>
</div>
</div>
The script which loads the newValue is this:
$(".href-select").click(function() {
var propName = $(this).text();
var propVal = $(this).attr('itemprop');
var json = JSON.parse(propVal, 'UTF-8');
var count = 0;
for (i in json) {
console.log(json[i]);
count++;
}
console.log(count);
$("#newProperty").attr('readonly', true);
$("#newProperty").val(propName);
$("#newValue").val(propVal);
$("#savePropertyBtn").hide();
$("#updatePropertyBtn").
});
I have modded the script to get the individual values from the JSON.
My idea is : to increment the count as I read the JSON values and then use this to add count number of span & textarea elements in the html through iteration. Also I want to add the count in the html and hide it so that I can get the count in the request object as well ( I will be creating a map with the number of values ).
Please help me in achieving my idea.
EDIT : This is what is expected if the JSON contains two pairs.
<div class="input-group input-group-lg">
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
</div>
EDIT 2: This is how the dialog box looks right now :
The value textbox contains the JSON. Now I want the textbox to look like this:
Name: [test222]
Host: [DS01ATA]
Port: [ 22 ]
You have to get the div first, then call the append function on it. For example, if you did $(".input-group"), that would give you a list of all html elements with a class of input-group (notice the period before the class name in the selector). Remember, classes aren't guaranteed unique, so my example is only unique if you only use that class once. Once you have the desired element, you can manipulate that element. In this case, you want to add an HTML element to the div.
$(".input-group").append("<span>Sample html string</span>");
References:
Docs for append: http://api.jquery.com/append/
CSS selector "playground" (with documentation): http://codylindley.com/jqueryselectors/
To copy - paste a div using jQuery
function copyDiv(divId) {
var content = $(divId).html();
var newdiv = $('<div>');
newdiv.html(content);
$(divId).after(newdiv);
return newdiv;
}
Calling copyDiv('#mydiv') will create a div with same content below #mydiv.
jQuery .clone() may also be useful here.
For your case, this function can be called inside your loop
for (i in json) {
var newdiv = copyDiv('#form-div-id');
... // add values to new div like 'i' and json[i]
}

How to hide, when page starts, html element generated automatically with jQuery

When page starts, jQuery produce a form that I want it to be hidden. Because I want to show it when I click on a button.
With these instructions I create the form:
$("#cards").append('<li id="card" class="feed-element animated fadeInRight" style="color: grey" data-user="' + key + '">\n\
<button id="previewCard" type="button" value = "' + key + '" class="btn btn-primary btn-sm btn-block btn-xs">' + preview + '</li>\n\
<form id="cardFormDetail" class="animated fadeInRight">\n\
<div class="form-group">\n\
<input id="customerCardDate" class="form-control" type="text">\n\
</div>\n\
<div class="form-group">\n\
<input id="customerCardScope" class="form-control" type="text">\n\
</div>\n\
<div class="form-group">\n\
<textarea id="customerCardText" class="form-control" rows="5"></textarea>\n\
</div>\n\
</form>\n\
<button id="modifiedCard" type="button" value = "' + key + '" class="btn btn-primary btn-xs pull-left">Modified</button>\n\
<button id="deleteRequestCard" type="button" value = "' + key + '" class="btn btn-primary btn-xs pull-right">Delete</button>\n\
<br><hr style="border-color: #c80b00;">');
When page starts cardFormDetail form is visible. How can I make it not visible?
I tried with $("#cardFormDetail").hide() but it doesn't work. And the reason is because it is a dynamic element, right?
Since you want to hide it on load, pls use CSS as opposed to jQuery unless there is a reason to justify why you want to do it so.
#cardFormDetail { display: none; }
put your code which hides the form after the code where it appends the element to the.
Another things is you are appending an element with the same id 'cards' to an existing element which has the same id.
It doesn't matter if your element is dynamically added, you should always be able to hide it using jquery.
Can you post the whole code?

How come my input box's value isn't being returned?

Using twitter bootstrap, I have created a button with an input box beside it. I'm trying to then access that value in my view using jQuery but for some reason I can't get anything back besides "undefined". Here's my code:
jQuery:
var browserInput = $("#browserInput").val();
console.log(browserInput);
Html:
<div class="col-lg-4">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" id="addBrowser">
<span class="glyphicon glyphicon-plus"></span>
Add
</button>
</span>
<input id="browserInput" type="text" class="form-control" style="display: none;" >
</div>
</div>
If this is your actual code layout, you won't get a value because the DOM isn't loaded at the time you are requesting the value.
You should try to wrap your function in document ready
$(document).ready(function() {
var browserInput = $("#browserInput").val();
console.log(browserInput);
});
If you want to have the value on keyup or interaction with the input box, you can also do it like
$(document).ready(function() {
$('#browserInput').on('keyup',function() {
var browserInput = $("#browserInput").val();
console.log(browserInput);
});
});
I'm going to undelete my answer because apparently it helped the poster solve his issue...
<input id="browserInput" type="text" value="" class="form-control" style="display: none;" />
Seems that having the value="" in the <input> tag made a difference for him.
I wonder if he meant "" instead of undefined.

Categories