Counting the number of appended elements for form submission - javascript

I have a web page that is a dynamic form. It allows users to specify any number of Attributes to devices. These attributes can be select option lists. When the user selects this, they are presented with a button to add options.
My problem is that I need to know how many options there are for each attribute. I have tried using var counter=$('.class-name').next().val(); to try and count them alert(counter); to see if it works. But all I get is an alert of undefined so the var counter is not being initalised.
I need to know the number of options for each select list to be able to group them together and know which options go with a particular attribute. I cannot think of a way to do this through JS or PHP. I can get the options posted in the php but I can't identify what options go with each attribute.
Here is a fiddle!

Here is the code to get the lengths for each of the respective options.
$('.tattribute option:selected[value="text"]').length
$('.tattribute option:selected[value="checkbox"]').length
$('.tattribute option:selected[value="select-list"]').length
$('.tattribute option:selected[value="notes"]').length
Fiddle
Here is a fiddle with a hidden field added to keep track of the options count. Every time an option is added or removed the value of the hidden field is incremented or decremented. The changes are in the code below
var template="<div class=\"new-attribute\">"
+ "<h3>New Attribute</h3>"
+ "<label for=\"attributeName[]"+"\">Name:</label>"
+ "<input class=\"attribute\" type=\"text\" name=\"attributeName[]"+"\">"
+ "<input class=\"attribute_count\" type=\"hidden\" name=\"attributeCount[]"+"\">"
+ "<label for=\"attributeType[]"+"\">Type:</label>"
+ "<select class=\"tattribute\" name=\"attributeType[]"+"\">"
+ "<option value=\"text\" selected>Text</option>"
+ "<option value=\"checkbox\">Checkbox</option>"
+ "<option value=\"select-list\">Select Option List</option>"
+ "<option value=\"notes\">Notes</option>"
+ "</select>"
+ "<div class=\"option\"></div>"
+ "<button type=\"button\" class=\"remove\">Delete</button>"
+ "</div>";
And
//Add action
$("#attributes").on('click', '.btn', function () {
add = "<div class=\"op\"><label for=\"attributeOption[]" +"\">Name:</label>"
+ "<input class=\"option-input\" type=\"text\" name=\"attributeOption[]" + "\">"
+"<button type=\"button\" class=\"remove-option\">remove</button></div>";
$(this).after(add);
//COUNT NUMBER OF OPTIONS
$opt = $(this).closest('.option')
$opt.siblings('.attribute_count').val($opt.find('.op').length)
alert($opt.siblings('.attribute_count').val());
});
//Remove input
$("#attributes").on('click', '.remove-option', function () {
$(this).closest('.op').remove();
$opt = $(this).closest('.option')
$opt.siblings('attribute_count').val($opt.find('.op').length)
});

Related

textarea clears when using innerhtml [duplicate]

I have a problem concerning multiple file uploads in javascript. I am trying to create my own multiple file upload by dynamically adding inputs. This is all easy as pie, but the problem is that whenever I add a new , my previous input-fields of the type "file" get reset.
If I remove the last lines of code where I alter the innerHTML of my parent div, the values of my do not get reset. Does anyone know how this problem can be solved? The javascript code can be found below. Thanks in advance.
if(document.getElementById("upload_queue").innerHTML.indexOf(_item) == -1)
{
var _row = "<tr id='queue_row_" + items_in_queue + "'>";
_row += "<td>";
_row += "<div class='remove_uploaded_image' onclick='remove_from_queue(" + items_in_queue + ")'></div>";
_row += "</td>";
_row += "<td>";
_row += _item;
_row += "</td>";
_row += "</tr>";
document.getElementById("upload_queue").innerHTML += _row;
document.getElementById("upload_image_" + items_in_queue).style.display = "none";
items_in_queue++;
document.getElementById("uploader_holder").innerHTML +=
'<input id="upload_image_' + items_in_queue +
'" name="upload_image_' + items_in_queue + '" accept="image/jpeg" type="file"' +
'onchange="add_to_upload_queue()" style="display: inline;" />';
}
Yeah... you're going to want to use appendChild instead of modifying the inner HTML:
var myInput = document.createElement("INPUT");
// do stuff to my input
var myContainer = document.getElementById("uploader_holder");
myContainer.appendChild(myInput);
That's the general gist of what you have to do - let me know if you need somethign more specific, but it looks like you've got a good hold on JS already... You're going to want to do that in almost all cases rather than setting inner HTML... So, building your TR as well... you'll have to append the TD to the TR, you'll have to append the TD with your input, you'll have to append your targeted table with the TR, etc.

Javascript onclick change content of HTML

I am adding new div when user clicks the blue button but everytime user click button, content of whole html is getting dissappeared i need a solution for it.
Also, is it possible to add an animation to it?
here is the demo just press blue button, type something and hit blue button again.
https://jsfiddle.net/61tbq4q6/2/
This is html part:
<input type="button" id="ebookParts" value="" class="custBut">
<div id="myContainerDiv">
</div>
This is the JS:
var i = 1;
$( "#ebookParts" ).click(function() {
var container = document.getElementById("myContainerDiv");
var html = document.getElementById('myContainerDiv').innerHTML;
html = html + "<div class=\"col-sm-12\">"
+ "<div class=\"form-group\">"
+ "<div class=\"col-sm-6\"><label>Name</label><input class=\"form-control\" type=\"text\" name=\"display_name[]\"></div>"
+ "<div class=\"col-sm-2\"><label>Part</label><input class=\"form-control\" type=\"text\" name=\"part[]\" value=" + i + "></div>"
+ "<div class=\"col-sm-2\"><label>Pages between</label><input class=\"form-control\" type=\"text\" name=\"pages[]\"></div>"
+ "<div class=\"col-sm-2\"><label>price</label><input class=\"form-control\" type=\"text\" name=\"price[]\"></div>"
+ "</div>"
+ "</div>";
container.innerHTML= html;
i++;
return false;
});
If you're saying the problem is that whatever the user manually typed into an input is disappearing, it's because you're destroying those inputs and replacing them with new ones when you do container.innerHTML = html. Your original assignment to var html = ... only captures actual attributes, not JS properties.
What you need to do if you're going to append new DOM elements using HTML, while keeping the old content, is to use .insertAdjacentHTML instead of .innerHTML.
This way, instead of taking the existing DOM, converting it to HTML markup, adding more HTML to it, and replacing the old DOM elements with new ones generated from the HTML, you'll be simply creating the new ones from the HTML and adding them where you want them.
var i = 1;
$( "#ebookParts" ).click(function() {
var container = document.getElementById("myContainerDiv");
var html = "<div class=\"col-sm-12\">"
+ "<div class=\"form-group\">"
+ "<div class=\"col-sm-6\"><label>Name</label><input class=\"form-control\" type=\"text\" name=\"display_name[]\"></div>"
+ "<div class=\"col-sm-2\"><label>Part</label><input class=\"form-control\" type=\"text\" name=\"part[]\" value=" + i + "></div>"
+ "<div class=\"col-sm-2\"><label>Pages between</label><input class=\"form-control\" type=\"text\" name=\"pages[]\"></div>"
+ "<div class=\"col-sm-2\"><label>price</label><input class=\"form-control\" type=\"text\" name=\"price[]\"></div>"
+ "</div>"
+ "</div>";
// The "beforeend" parameter inserts the new content inside the
// container after the existing content.
container.insertAdjacentHTML("beforeend", html);
i++;
return false;
});
It's because you getting html, than changing it an then inserting again in your page. When you copying your html, you don't copying values, which already passed in inputs. Instead of this you need to use .appendChild() method, and you will also need document.createElement()
If you need only to add the div one time. Then check with a "if" before add the div.
var isAdded=false;
$( "#ebookParts" ).click(function() {
if(!isAdded){
//your code
}
});

Dynamically add "select" with "default Text" in table through javascript

How can I add dynamical drop down selects(set default selecte!) in dynamically table by using javascript and JSON.
I want to add many selects (dropdown) to every row in my table, and set the default text in the select. The table is created by using javascript append and has dynamic content imported from JSON files using Jquery.
I can import all content successfully, however the dropdowns can not set selected . I would appriciate if you guys can assist me to have the dropdown select. Thank you very much!
<script type="text/javascript">
...
$(target).append("<tr style='height:150px'>" +
"<td><input type='checkbox'></td>" +
"<td>pics</td>" +
"<td>" + menuItemName + "</td>" +
"<td id='"+menuItemId+"'>" +
"</td>" +
"<td class='menuItemPrice'>" + menuData.Categories[c].Items[i].Price + "</td>" +
"<td>mount</td>" +
"</tr>"
);
...
for (var o = 0; o < menuData.Categories[c].Items[i].Options.length; o++) {
var inputs = {isFirst: firstOption,
optionId: menuData.Categories[c].Items[i].Options[o].MenuItemOptionId,
optionName: menuData.Categories[c].Items[i].Options[o].MenuItemOptionName,
price: menuData.Categories[c].Items[i].Options[o].Price
};
$('#'+menuItemId).append("<div><select"+
"<option value='1'>small</option>" +
"<option value='2'>mid</option>" +
"<option value='3'>big</option>" +
"<option value='4'>very big</option>"+
"</select></div>"
);
here I want to set the default Select but can not success,please help me,Thank You!
$('#'+menuItemId).children(':selected').text(inputs.optionName);//here just can show the last size.
HTML
...
<tbody id="sortable">
First, your select tag does not have a closing angle bracket (>) so the HTML is malformed. It should be something like this:
$('#'+menuItemId).append("<div><select>"+
Second, you should use find instead of children because what you are looking for is multiple levels below the element identified by your selector, like so:
$('#'+menuItemId).find(':selected').text(optionName);
Here is a working example: https://jsfiddle.net/tLddsL2p/1/

access dropdown value generating on runtime

I am using C# asp.net. On button click I am generating a dropdown by using Javascript.
<scripttype="text/javascript">
var counter = 0;
function AddFileUpload() {
//debugger;
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '"Type="file"/>' +
'<select id="Droplist' + counter + '" name="droplst"/>' +
'<option value="SCR">Student Count request</option>' +
'<option value="DRO">Documents recieved from others</option>' +
'<option value="TE">total estimates</option>' +
'<option value="PRE">Presentation</option>' +
'<option value="PRI">Pricing</option>' +
'<option value="Quest">Questions to student</option>' +
'<option value="RelvExp">RelevantExperience-Case Studies</option>' +
'<option value="ResReq">Resource requests</option>' +
'<option value="SSP">Student submitted paper</option>' +
'<option value="WIP">WIP</option>' ;
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
</script>
I am accessing the dropdown values in page behind like this
string val = Request.Form["droplst"];
It is working fine,but what I am receiving is option value. Like "SCR" when "Student Count request" is selected. is there any way to access the selected value like "Student Count request" instead of getting the option value?
Please let me know if the question is vague and further clarification is required.
Are the values of the options necessary? The easiest change to make would be to remove the values. E.g:
<option>Student Count request</option>
If you do require the values, then it's a bit more tricky: you have added the dynamic control to the page using JavaScript, so the code behind won't be able to find it easily. You could add an ASP HiddenField control to the page, then when a dropdown is selected, populate that hiddenfield with the text value using JQuery/JavaScript. Then in the code behind you can access the value of the hidden field (which will be the dropdown selected text).
Do you understand? You can read further here which is a duplicate of this question and has already been answered: How to access dropdown text (not value) using Request.Form()?

Javascript selected item value not pulling correctly

I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"
What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=
I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
console.log(selection);
$('#right').empty();
var addNewFields = 'these will be the fields';
$('#right').append(addNewFields);
}
Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>
This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
$('#userSelection').append(optionTag);
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';
Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
value: $(this).find('optionID').text(),
html: $(this).find('optionName').text()
});
When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
changeFn(this.options[this.selectedIndex].value);
};

Categories

Resources