Having a difficulty adding a new form in each new <div> - javascript

In my adventure to create a To-Do list application, I've run into another problem. In my code, every time a user clicks New Category a new div will appear with their custom name and number of forms.
However, when another div is created, its' forms are given to the previous div. Here's that code:
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type='text/javascript' src="script.js"></script>
<script>
$(function() {
$("#new").click(function() {
var canContinue = true;
var newCategory = prompt("Enter the name you want for your category:");
if(newCategory.length === 0){
confirm("A new category can not be created - nothing was entered in the text area.");
canContinue = false;
}
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
$("body").append("<div id = \"newDiv\"><p>" + newCategory + "</p></div>");
}
for(var i = 0; i < categorySections; i++){
$("#newDiv").append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
</script>
So, I tried creating a separate function using the this keyword where the forms were created after the div was ready, but now no forms are created at all!
Here's that code:
$(function(){
$("#newDiv").ready(function() {
for(var i = 0; i < categorySections; i++){
$(this).append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
So, how do I create forms for each separate div?

You're repeatedly creating divs with the same ID. (a) that's not legal and (b) if you do it anyway, your $(#newDiv) selector will always apply to the first one.
Also, you're appending to #newDiv outside the if (canContinue) check.
Try:
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
var newDiv = $("<div>").appendTo($(document.body));
var header = $('<p>').text(newCategory).appendTo(newDiv);
for(var i = 0; i < categorySections; i++){
newDiv.append("<form> Thing to do: <input type = \"text\"></form><br>");
}
}

jsFiddle
You can't use the ID newDiv multiple times, HTML IDs must be unique. Additionally, your flow can be cleaned up a bit, as below.
$(function () {
$("#new").click(function () {
var newCategory = prompt("Enter the name you want for your category:");
if (newCategory.length === 0) {
confirm("A new category can not be created - nothing was entered in the text area.");
return false;
}
var categorySections = prompt("Enter the number of sections needed for this category:");
var $div = $("<div />", {
html: "<p>" + newCategory + "</p>"
});
$("body").append($div);
for (var i = 0; i < categorySections; i++) {
$div.append("<form> Thing to do: <input type='text'/></form><br>");
}
});
});

Related

How to do this the with Jquery instead of javascript

I've been trying to convert this section of script to jQuery instead of vanilla javascript, but I'm not sure how to loop through the elements with jQuery. Basically, I'm grabbing a data attr value from each field to be used as an error message that displays near the field.
This is all inside a click event on the submit button, FYI
What's the jQuery way?
//Set some variables
var invalidFields = $(form).querySelectorAll(':invalid'),
errorMessages = $(form).querySelectorAll('.error-message'),
parent;
// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[i]);
}
//Get custom messages from HTML data attribute for each invalid field
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
//Display custom messages
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.insertAdjacentHTML('beforeend', '<div class='error-message'>' +
invalidFields[i].validationMessage +
"</div>");
}
I converted your code one-to-one to jQuery. But there might be other ways, when i will know where form, setCustomValidity and validationMessage is coming from.
var $form = $(form);
// Remove any existing messages
$(".error-message", $form).remove();
// Get custom messages from HTML data attribute for each invalid field
$(".sdForm-input", $form).each(function() {
var message = $(this).attr('data-ErrorMessage');
// i don't know where the 'setCustomValidity' function is coming from
// this is a custom function
$(this)[0].setCustomValidity(message);
});
// Display custom messages
$(":invalid", $form).each(function() {
// i don't know where 'validationMessage' is comig from
// this is a custom property
$(this).parent().append("<div class='error-message'>" + $(this)[0].validationMessage + "</div>");
});
You can simple replace this.
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
Replace with jQuery way
var fields = form.find('.sdForm-input');
$.each(fields, function(index, el){
var message = $(el).attr('data-ErrorMessage');
$(el).setCustomValidity(message);
});

how to get username via checked checkbox with javascript or jquery?

i
HTML
<div id="notApprovedUsers">
</div><button onclick="approveUsers()">Approve</button>
</div>
i like to get checked users in parameter userList to work with.
here is javascript there me generating list with users and checkboxes.
i like to approve just the checked one's of course!
JavaScript
function getNotAssignedUsers() {
server.getUsersByGroup("1eb33e30-c355-467f-af3c-e7d0b4a1fgt5").then(function (userDetails) {
debugger;
for (var i = 0; i < userDetails.length; i++)
{
var vorname = userDetails[i].firstName;
var nachname = userDetails[i].lastName;
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = "0"+i;
document.getElementById("notApprovedUsers").appendChild(newCheckBox);
var newElement = document.createElement('div');
newElement.id = i;
newElement.className = "notApprovedUsers";
newElement.innerHTML = vorname + " " + nachname;
document.getElementById("notApprovedUsers").appendChild(newElement);
}
});
}
HERE in userList I need to read just a checked users..
function approveUsers(userList)
{
var user1 = document.getElementById("00").checked;
var user2 = document.getElementById("01").checked;
var user3 = document.getElementById("02").checked;
alert(user1 || user2 || user3);
}
You want something like this then. There may be errors as I havent tested
var names = [];
$('input[type=checkbox]:checked').each(function(index, value){
var name = $(value).next("div").html();
names.push(name);
});
Then do something with the names array
Edit - See jsfiddle http://jsfiddle.net/vpg3r/3/
I think the best solution for you here is to use jQuery. You can use something like:
$('#notApprovedUsers input[type=checkbox]:checked')
to get all the elements that are checked, and work with them.
I've created a JSFiddle for you to demonstrate how to implement the behavior that I'm describing. You can see it in this link.

Javascript Multiple Dependant Dropdowns

I am new to javascript and I'm struggling with the following code that will be in a form for registration of multiple candidates.
It creates 2 dependant select boxes (country and area) for each candidate.
Clicking the button 'Add Candidate' once allows the dependant boxes to work fine but clicking the button again stops it working. Accessing the selected values from the form when there is more than one candidate is also impossible as they will overwrite each other.
I have tried creating the select names as arrays using a count variable which I increment each time the ff function is called but I can't get it to work.
All help will be much appreciated!
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<title>Select Populate Test</title>
<script>
var UnitedStates = new Array();
UnitedStates[0] = "Texas";
UnitedStates[1] = "California";
UnitedStates[2] = "Arizona";
UnitedStates[3] = "Nevada";
UnitedStates[4] = "Florida";
var UnitedKingdom = new Array();
UnitedKingdom[0] = "Surrey";
UnitedKingdom[1] = "Kent";
UnitedKingdom[2] = "Dorset";
UnitedKingdom[3] = "Hampshire";
function populateDropdown(arry)
{
document.myForm.stateSelect.options.length = 0;
for (var i = 0; i < arry.length; i++)
{
document.myForm.stateSelect.options[i] = new Option(arry[i], arry[i]);
}
}
function updateDropdown(str)
{
var stateArray
var selectedCountry;
var countryDropdown = document.myForm.countrySelect;
for (var i = 0; i < countryDropdown.options.length; i++)
{
if (countryDropdown.options[i].selected)
{
selectedCountry = countryDropdown.options[i].value;
}
}
if (selectedCountry == 1)
{
stateArray = UnitedStates;
populateDropdown(stateArray);
}
if (selectedCountry == 2)
{
stateArray = UnitedKingdom;
populateDropdown(stateArray);
}
}
counter = 0;
function ff()
{
counter++;
var box = document.getElementById("details"+counter);
var cselectBox = document.createElement("Select");
cselectBox.name="countrySelect";
cselectBox.onchange = function()
{
updateDropdown();
}
var option1 = document.createElement("OPTION");
option1.text="United States";
option1.value=1;
cselectBox.options.add(option1);
var option2 = document.createElement("OPTION");
option2.text="United Kingdom";
option2.value=2;
cselectBox.options.add(option2);
document.getElementById("details"+counter).innerHTML+="</p><p>"+counter+". Candidate Country";
box.appendChild(cselectBox);
var box2 = document.getElementById("detailsx"+counter);
var ccselectBox = document.createElement("Select");
ccselectBox.name="stateSelect";
document.getElementById("detailsx"+counter).innerHTML+="</p><p>"+counter+". Candidate City";
box2.appendChild(ccselectBox);
}
</script>
</head>
<body>
<form name="myForm" >
<input type="button" value="Add Candidate" onClick="ff(); populateDropdown(UnitedStates);"">
<!--- Note: 6 Candidates will be the maximum. -->
<div id="details1"><b></b></div>
<div id="detailsx1"><b></b></div>
<div id="details2"><b></b></div>
<div id="detailsx2"><b></b></div>
<div id="details3"><b></b></div>
<div id="detailsx3"><b></b></div>
<div id="details4"><b></b></div>
<div id="detailsx4"><b></b></div>
<div id="details5"><b></b></div>
<div id="detailsx5"><b></b></div>
<div id="details6"><b></b></div>
<div id="detailsx6"><b></b></div>
</form>
</body>
</html>
There are multiple problems here. We'll tackle the one you're dealing with first.
When you name multiple controls with the same name, like stateSelect, you'll get the first one each time you try to reference it. If you instead set the id to 'stateSelect' + counter, you'll get a unique id, which you can then retrieve with document.getElementById(). So in the function to populate the dropdown would look like this:
function populateDropdown(arry)
{
var stateSelect = document.getElementById('stateSelect'+counter);
stateSelect.options.length = 0;
for (var i = 0; i < arry.length; i++)
{
stateSelect.options[i] = new Option(arry[i], arry[i]);
}
}
here is the fiddle I used to verify those changes.
You'll also need to add an event to each country dropdown to repopulate the state dropdown when it changes, and the structure needs a little work for that. If you're not opposed to frameworks, knockout would make this incredibly simple to run.
Here is the fiddle with everything working correctly and comments added at key changes
Update: Added link to the fiddle(s)

Dynamically generating a button using DOM and editing onclick event

I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}​
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.

Javascript custom validation

I'm writing a custom javascript validation script whereby i iterate through all input elements in a div named 'toggle' and select each that has a class named 'required' and if the value of the element is an empty string (empty) then i need to create labels containing the error message and place them right next to the textbox.
Here's the code:
function clientErrMsgs() {
var container = document.getElementById("toggle");
var inputArray = container.getElementsByTagName("input");
for (var i = 0; i < inputArray.length; i++) {
alert("");
if (inputArray[i].getAttribute("class") == "required" && inputArray[i].value == "") {
var errmsg = inputArray[i].getAttribute("data-errormessage");
var labelErr = document.CreateElement('label');
labelErr.id = "ErrMsg" + i;
labelErr.value = errmsg;
var parent = inputArray[i].parentNode;
parent.appendChild(labelErr);
}
}
}
the program executes well (tested it with alert()) up until the following line:
var labelErr = document.CreateElement('label');
Where is the problem?
you can use asp.net custom validator to do this
i am giving you an example, how to do this....
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Sms length is exceeding over 160."
ClientValidationFunction="validateLength" ControlToValidate="txtSmsMessage"
SetFocusOnError="True" ValidationGroup="add">*</asp:CustomValidator>
<script language="javascript" type="text/javascript">
function validateLength(oSrc, args)
{
args.IsValid = (args.Value.length < 160);
}
</script>
i suggest please try this...
I got things working with:
http://jsfiddle.net/ahallicks/kxPeN/2/
labels don't have a value attribute
Its document.createElement not document.CreateElement
MDC link : document.createElement
Update: you should access the innerHTML of the label and not the value
The snippet
var labelErr = document.createElement('label');
labelErr.id = "ErrMsg" + i;
labelErr.innerHTML= errmsg;
var parent = inputArray[i].parentNode;
parent.appendChild(labelErr);
This is not a direct answer to your question, but would your superior go for a different pre-built validation method? I'm partial to FlowPlayers jQuery based validator. Very simple to setup:
$("#myform").validator();
I've written several validation frameworks in the past. I finally got tired of reinventing the wheel.
May I suggest this:
function clientErrMsgs() {
var container = document.getElementById("toggle");
var inputArray = container.getElementsByTagName("input");
for (var inp, i=0, n=inputArray.length; i<n; i++) {
inp = inputArray[i];
if (inp.getAttribute("class") === "required") {
var errMsg = container.getElementById("ErrMsg"+i);
if (!errMsg) {
errMsg = document.createElement('span');
errMsg.id = "ErrMsg" + i;
errMsg.innerHTML= inp.getAttribute("data-errormessage");
inp.parentNode.appendChild(errMsg);
}
errMsg.style.display= (inp.value === "")?"":"none"
}
}
}

Categories