Show div and create elements any time a checkbox is checked - javascript

I'm trying to show div#options_holder and create some elements inside it by using this code:
var counter = 1;
$('#choices').on("change", ":checkbox", function(e) {
var theName = $(this).attr('name');
var theID = $(this).attr('id');
var isChecked = $(this).prop("checked");
var input, button, append = "";
$("#options_holder").show();
input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';
append = counter === 1 ? input += button : input;
$("#options_holder").append(append);
counter++;
console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});
But it does not work since div#options_holder remains hidden and elements aren't created, is something wrong? It's supposed that those should happen any time I mark a checkbox, if I unmark in the other hand the process should be reverted meanind div#options_holder will be hidden and any element inside it should be destroyed, what's wrong?

Making sure that your selectors work and your IDs are correct are often easily overlooked. Glad we could help you find your typing mistake :-)
Working code fiddle: http://jsfiddle.net/pXJpr/
HTML:
<div id="choices">
<input type="checkbox" name="testName" id="testId" />
</div>
<div id="options_holder" style="display:none;">
</div>
JS:
var counter = 1;
$('#choices').on("change", ":checkbox", function(e) {
var theName = $(this).attr('name');
var theID = $(this).attr('id');
var isChecked = $(this).prop("checked");
var input, button, append = "";
$("#options_holder").show();
input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';
append = counter === 1 ? input += button : input;
$("#options_holder").append(append);
counter++;
console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});
function capitalize(s) {
return s;
}

Related

Toggle function problem, What am I doing wrong?

I've created a comment system that posts comments in an ordered list. My requirememnts were to add hide/show toggle function to each comment.
Currently, the toggle function only works on the first comment (even when you try to click on 2nd, 3rd, etc.)
I've tried to use querySelectAll, but it didn't work for me. What am I doing wrong?
<div class="textbox">
<h3>Leave comments</h3>
<label for=msg>Name</label><br>
<input type=text id=fname> <br>
<label for=msg>Content</label><br>
<textarea id=msg> </textarea>
<br>
<input type=button onclick="postcomments()" value="Send" />
<input type="reset" value="Reset" />
<ol id="showcomments" style="max-width:200px; font-size:12px; padding-left:10px;">
</ol>
</div>
<script>
var ans = [];
function postcomments() {
var fname = document.getElementById("fname").value;
var msg = document.getElementById("msg").value;
var lastpos = ans.length;
var current = new Date();
console.log(current);
var time = current.getHours() + ":" + (current.getMinutes() < 10 ? '0' : '') + current.getMinutes();
var date = current.getDate() + "." + (current.getMonth() + 1) + "." + current.getFullYear();
var i = 0;
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(document.getElementById("txt&quot))" style="width:8%;" id="plusminusicon">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
var ol = document.getElementById("showcomments");
ol.innerHTML = "";
for (var i = 0; i < ans.length; i++) {
ol.innerHTML += "<li id=" + (i + 1) + ">" + ans[i] + "</li>";
}
}
function toggle(x) {
if (x.style.display === "none") {
x.style.display = "block";
document.getElementById("plusminusicon").src = "Media/minusicon.png";
} else {
x.style.display = "none";
document.getElementById("plusminusicon").src = "Media/plusicon.png";
}
}
</script>
You have always the same id for all "txt" span, so the browser change always the first.
If you don't want change much of your code the simpliest solution is add the lastpost variable to the span id and to the parameter of toggle function.
Here the changes to do:
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(' + lastpos + ')" style="width:8%;" id="plusminusicon' + lastpos + '">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt' + lastpos + '" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
function toggle(x) {
let comment = document.getElementById("txt" + x);
let icon = document.getElementById("plusminusicon" + x);
if (comment.style.display === "none") {
comment.style.display = "block";
icon.src = "Media/minusicon.png";
} else {
comment.style.display = "none";
icon.src = "Media/plusicon.png";
}
}
To bind click listeners to dynamically added elements, you can use event delegation.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('comment')) {
// do something
}
})
jQuery makes it even easier.
$(document).on('click','.comment',function(){ //do something })
And here's a jsfiddle link to the complete code example. https://jsfiddle.net/ep2bnu0g/

Jquery Can't append option Filed in Select

I am having problem to append <option> in <select> as my scenario is I am showing all list if users want to add their own option so I am opening model and take input from user
And problem is I am not able append user input with their specify Select option
as I have add more options to
HTML:
<li style="width: 27%;">
<label class="select">
<span style="display: inline-block;padding: 10px 0;">Institute:</span>
<select name="institute[]" id="institue1" onchange="Myinsi(this.value, 'institue1')" class="validate[required] institute" style="width: 65%;float: right;">
<option value="">Select</option>
<?php
$sel = "select * from institute where `status`= 'Y'";
$res = mysql_query($sel);
while ($row = mysql_fetch_assoc($res)) {
echo "<option value='{$row['title']}'>{$row['title']}</option>\n";
}
echo'<option value="ShowOtherIns" id="ShowOtherIns">Other</option>';
?>
</select>
<i></i>
</label>
</li>
jQuery Code:
<script>
function Myinsi(value, id) {
console.log(value + '----' + id);
var index = $(id + ' option').length + 1;
if (value == "ShowOtherIns") {
$('#OtherIns').modal("show");
document.getElementById("btnSave").onclick = function () {
var NewText = document.getElementById('OtherInsTextID').value;
if (NewText = !'') {
var element = document.getElementById(id); // assuming ul exists
$(id).append('<option value="' + NewText + '" selected="selected">' + NewText + '</option>');
$('#OtherIns').modal("hide");
} else {
console.log("text = exibir menu");
}
};
}
}
</script>
I am attaching my screen shoot too
Jquery selector is incorrect. You have to write "#" followed by the id of your html element. In the line var index = $(id + ' option').length + 1; you should write var index = $('#'+id + ' option').length + 1;.
Also in the line $(id).append('<option value="' + NewText + '" selected="selected">' + NewText + '</option>'); you should write $('#'+id).append('<option value="' + NewText + '" selected="selected">' + NewText + '</option>');

passing value to a dynamic created function in javascript

I am having some problems while creating a dynamic webpage in javascript.
My idea is to read a list of events and people signed up on them. I create a page with all events (each event is a button) and clicking on one of them, see the list of users.
This works fine. But now, I am adding a button to export some of these users to an excel file. And I want to add a button with an onClick function like this:
...onclick=functionÇ(id_Event, numberOfUsers, listOfUsers)...
Inside of the html code generated by javascript. I found some problems also doing like this so I changed so:
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
I created a global array called arrayNumberUSersInEvents in which I am adding in each possition, people subscribed. i, is the id counter for each position.
But even this, I am getting an undefined while reading the value of the firsdt parameter. I think it is a problem of dynamic data, I am not executing the function I want to each time I click the button. Do you know how to do something like this?
To sum up: My problem is that I want to pass some arguments to a function in a dynamic created page. I don't know how to pass the data and read the correct parameters inside.
I added my code because one user asked for it:
for(i = 0; i < element.length; i++){
$(".eventsControl").append(
'<li id="listControl'+ element[i].id_Event +'">'+
'<a href="#EventControl' + element[i].id_Event + '"' + 'data-transition="slidedown">'+
'<img class="crop" src= "' + element[i].image + '" />'+
'<h2>' + element[i].name + '</h2>'+
'<p>' + "Desc: " + element[i].description +'</p>'+
'</a>'+
'</li>'
).listview('refresh');
//console.log(response);
//BUCLE for setting all users in each event. Better use some string and after, join all of them
header = ' <div width="100%" data-theme = "e" data-role="page" id='+ element[i].id_Event +
' data-url="EventControl' + element[i].id_Event + '"> ' +
' <div data-theme = "a" data-role="header"><h1>Lista de Asistencia</h1> ' +
' </div>'+
' <div data-role="content"> ' +
' <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center">' +
' <div style="width: 500px; margin: 0 auto;">';
//header = header + '<input data-theme = "c" onclick="saveExcelFunctionControl(this)" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
eval('var numberUsers' +element[i].id_Event + "=1");
arrayNumberUsersInEvents[i] = 0;
if(response.length>0){
bucle = ' <table width="100%" border="1" align="left"><tr>'+
' <th>Nombre</th>'+
' <th>Primer apellido</th>'+
' <th>Segundo apellido</th>'+
' <th>NIF</th>'+
' <th>Asistencia</th>'+
' </tr>';
for(iData = 0; iData < response.length; iData++){
if(element[i].id_Event == response[iData].id_Event){
//console.log(response[iData].name);
bucle = bucle + '<tr><td>'+ eval('numberUsers' +element[i].id_Event) +'</td><td>'+ response[iData].name +'</td><td>'+
response[iData].surname1 +'</td><td>'+
response[iData].surname2 +'</td><td>'+
response[iData].NIF + '</td>'+
'<td> '+
'<input type="checkbox" id="checkBox'+element[i].id_Event+'_'+iData+'" name="option'+iData+'" value="'+iData+'"> '+
'</td>'+
'</tr>';
eval('numberUsers' +element[i].id_Event + "++");
arrayNumberUsersInEvents[i] = arrayNumberUsersInEvents[i]+1;
}
}
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(\""element[i].id_Event "\","" + numberUsers + "\",\"" + response+ "\"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(""+numberUsers+"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
bucle = bucle + '</table>';
$("#controlList").after(header + bucle + '<div id=added'+element[i].id_Event+'></div>');
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
}
}
},
error: function(xhr, status, message) { alert("Status: " + status + "\nControlGetEventsRegister: " + message); }
});
You can use closure to pass parameters to dynamically created onclick handler:
input.onclick = (function() {
var arr = arrayNumberUsersInEvents[i];
var resp = response;
return function() {
saveExcelFunctionControl(arr, resp);
}
})();
How do JavaScript closures work?
var td = document.createElement("td");
var input = "<input type='button' value='Exportar a Excel CSV'";
input+= "onclick='saveExcelFunctionControl(""" +arrayNumberUsersInEvents[i]+""","""+ response+""");' />";
};
td.textContent=input;
document.getElementById("added"+element[i].id_Event).appendChild(td);
try this way

different name for dynamically generated text field in jquery

This is a jquery to generate dynamic input text field in html.
TO give different name to each text field, 'num ' is incremented .
I even try ".attr('name', 'device' + num);"... But its not working .
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var num=0;
num++;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
**var fName = $("<input type=\"text\" class=\"fieldname\" name=\"' + num + '\" />");**
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
if 3 new text fields are generated now,
how can i add the value in each text field onkeyup
You override the num on each click, and messed up the string notations.
Put the num declartion outside the callback:
var num=0;
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
num++;
$('<input type="text" class="fieldname" name="' + num + '" />');
A tip of the day, in javascript you can use ' and " for strings notations, you them both and you won't need to escape the other notation.
There is a syntax error in your code, you mess with single and double quotes...
Should be something like this
var fName = $('<input type="text" class="fieldname" name="' + num + '" />');
OR:
var fName = $("<input type=\"text\" class=\"fieldname\" name=\"" + num + "\" />");

reload content not form for dropdowns

I am using a script to generate custom styled dropdowns out of my selects. Basically it creates a list out of the selects and hides the original select making it much easier to style than a <select> allows.
So the basic setup is like this
<div id="formdiv">
<form method="get" name="search" action="samepage">
inputs
</form>
content from form
I want the wrap section to be generated without refreshing the form part that way the dropdodwns dont keep disappearing and reappearing when the page loads.
here is my code for creating the dropdowns ( any performance tuning suggestions are welcome :) )
function createDropDown() {
var selects = $("select.createdrop");
var idCounter = 1;
selects.each(function() {
var dropID = "dropdown_" + idCounter;
var source = $(this);
var selected = source.find("option[selected]");
var options = $("option", source);
source.after('<dl id="' + dropID + '" class="dropdown"></dl>');
var imgtype = '<img src="images/transpx.gif" class="srcimg '+selected.text().toLowerCase()+'" />'
$("#" + dropID).append('<dt>'+imgtype + selected.text() + '<span class="value">' + selected.val() + '</span><img src="images/select-down-arrow.png" class="down-arrow" /></dt>');
$("#" + dropID).append('<dd><ul></ul></dd>');
options.each(function() {
$imgclasstxt = $(this).text().toLowerCase();
var srcimg = '<img src="images/transpx.gif" class="srcimg '+$imgclasstxt+'" width="10px"/>';
$("#" + dropID + " dd ul").append('<li>'+srcimg + $(this).text() + '<span class="value">' + $(this).val() + '</span></li>');
});
idCounter++;
});
}
and here is the code for selecting an option and submiting the form
$(".dropdown dd ul a").click(function() {
var dl = $(this).closest("dl");
var dropID = dl.attr("id");
var text = $(this).attr("id");
var source = dl.prev();
var typeicon = '<img src="images/transpx.gif" class="srcimg '+text.toLowerCase()+'" />'
$("#" + dropID + " dt a").html(typeicon+''+text+'<img src="images/select-down-arrow.png" class="down-arrow" />');
$("#" + dropID + " dd ul").hide();
var value = $(this).children("span.value").html();
source.val(value);
$(this).addClass('selected');
$('body').css('cursor','wait');
document.search.submit();
});
You're modifying the DOM a lot with this code. If it's slow, try dropping as many DOM changes as possible into a string first and then inserting it. You're also doing repeat selects in some places. Example:
$("#" + dropID).append('<dt>'+imgtype + selected.text() + '<span class="value">' + selected.val() + '</span><img src="images/select-down-arrow.png" class="down-arrow" /></dt>');
$("#" + dropID).append('<dd><ul></ul></dd>');
Could change to:
var html = '<dt>'+imgtype + selected.text() + '<span class="value">' + selected.val() + '</span><img src="images/select-down-arrow.png" class="down-arrow" /></dt><dd><ul></ul></dd>'
$("#" + dropID).append(html);

Categories