How to generate sequence number with jquery? - javascript

I had someone who did this script (credit Chyno Deluxe) that generate a list of menu whatever we write on the box, the question is, I need to generate a sequence of number that continuously added to it
here is the example needed,
<li id='item1'></li> <li id='item2'></li> <li id='item3'></li> <li id='item4'></li>
the number generated beside item'#' , 1,2,3,4,5,6
I had this that generate number, but it was fixed number, here
$.map($(Array(8)),function(val, i) { return i; })
this one only make like this
1,2,3,4,5,6,7,8
the script
(function($) {
"use strict";
var t2h = {
buildHTML: function() {
var i, list, type = this.htmlSelect.options;
if (type[1].selected) {
//console.log(type[1].text);
list = "<select>";
list += "\n";
for (i = 0; i < this.get_items().length; i++) {
list += " <option>";
list += this.get_items()[i];
list += "</option>";
list += "\n";
}
list += "</select>";
you can see the demo below with jquery code
that will generate
<select>
<option>menu 1</option>
<option>menu 2</option>
</select>
I need to improve it by adding tag id='' + number on it, like this
<select>
<option id='item1'>menu 1</option>
<option id='item2'>menu 2</option>
</select>
demo : [a link] http://codepen.io/diden/pen/YwwVKO
Hope I can get help with this here, Thank you guys :)

for (i = 0; i < this.get_items().length; i++) { // here i will go from 0 to the length of the items the select will have -1
list += " <option>"; // for each of these values of i, we add the first part of the html to list, which is a string variable
list += this.get_items()[i]; // this adds the ith text that the user wrote, but it´s 0 index based instead of starting with 1
So what you want is just add the id correlated to index of the line the user entered . And this is just i+1 !
So:
list += " <option id='item"+(i+1)+"'>"; // we open open and close "" to add (i+1) which is a varibale, and its the id we wanted

concatenate "item" with the iterator of your for loop plus one (i + 1). and set that as the id while looping through the items. (Note that i starts at zero so if you want it to start with 1 then you have to add 1 to it)

Related

Reset name attribute array indexes, dynamically add remove rows

I have to post data via ajax and need the name attribute array indexes to reset.
For example:
1st row:
<select data-placeholder="Colours" class="colours chosen-select"
multiple tabindex="4" name="colours[0][]">
<option value="">Red</option>
<option value="">Orange</option>
</select>
2nd Row dynamically added:
<select data-placeholder="Colours" class="colours chosen-select"
multiple tabindex="4" name="colours[1][]">
<option value="">Red</option>
<option value="">Orange</option>
</select>
The name colours array must increment by 1 everytime I add, as well as reset the values when I remove.
I have looked around but not found any solution.
Here is what I have:
Adding:
var tbl = $("#service");
$("#addRowBtn").click(function () {
var count = $('#rowCount tr').length;
$("<tr>" +
"<td>" +
"<select data-placeholder=\"Colours\" class=\"colours chosen-select\"
multiple tabindex=\"4\"\ name=\"colours[" +
count +
"][]\">" +
"<option value=\"\">Red</option>" +
"<option value=\"\">Orange</option>" +
"</select></td>" +
"<td><i style=\"color:#d64830\" class=\"delRowBtn fa fa-minus-
circle\"></i></td></tr>").appendTo(tbl);
Deleting a row:
$(document.body).delegate(".delRowBtn", "click", function () {
$(this).closest("tr").remove();
});
I have added var count to increment the indexes, but I'm not able to reset the values when removing.
Please help!
You can try to cycle all select of your table and change the attribute "name" of each select everytime you delete an item.
$('#rowCount tr td select').each(function(idx, item){
$(item).attr("name", "colours[" + idx + "][]")
});
update
like suggest #ChayimFriedman the cool version of previous suggestion
$('#rowCount select').attr('name', function(idx) { return "colours[" + idx + "][]"; });

How do I create a div and give it an ID based on a changing variable?

I'm making a quiz. The user decides how many questions he wants to answer.
A function then takes this number and runs a loop to make an individual question div for each question. The quiz shows a Chinese character and the user has to pick the correct translation.
My code:
var fillInQuestion = function() {
questionDivIdHTML = 'question' + questionNum;
/****************************************
How do I make this Div's ID = to questionDivIdHTML?
// Creates question div
$('#questionArea').append("<div class='questionDiv'></div>");
//$('#questionArea:last-child').attr("id", questionDivIdHTML); <-- NOT WORKING
***************************************/
// Sets up a choice bank.
var choices = [];
// choices will be chosen from this.
var tempAnswerSet = allChoices.slice(0);
//find random item in the database for the question
var thisQuestion = allQuestions[Math.floor(Math.random() * allQuestions.length)];
// add that item to choices
choices.push(thisQuestion);
// remove item from 'database' so it cannot be used in another question
allQuestions.splice(allQuestions.indexOf(thisQuestion), 1);
// remove item from tempAnswer set so it can only be one choice
tempAnswerSet.splice(tempAnswerSet.indexOf(thisQuestion), 1);
// add three more items from the database (incorrect items)
var i = 3;
for (i; i > 0; i--) {
var addChoice = tempAnswerSet[Math.floor(Math.random() * tempAnswerSet.length)];
choices.push(addChoice);
// remove the one selected each time so they cant be chosen again
tempAnswerSet.splice(tempAnswerSet.indexOf(addChoice), 1);
//console.log("choices length: " + choices.length);
}
// shuffle the array
choices.shuffle();
// fill in the div with choices.
$('#questionDivIdHTML').append("Here is an question prompt:" + thisQuestion.english + " <br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[0].hanyu</script>'></input>" + choices[0].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[1].hanyu</script>'></input> " + choices[1].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[2].hanyu</script>'></input> " + choices[2].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[3].hanyu</script>'></input> " + choices[3].hanyu + "<br>");
};
var fillOutQuiz = function() {
for (questionAmount; questionAmount > 0; questionAmount--) {
fillInQuestion();
questionNum += 1;
}
};
I've gotten this code to work, but I broke it, when trying to add the dynamic ID and loop it.
You are saying that this portion of code is not working:
$('#questionArea').append("<div class='questionDiv'></div>");
$('#questionArea:last-child').attr("id", questionDivIdHTML);
Well, it does not work because the :last-child pseudo selector is used incorrectly (see below). It should be:
$('#questionArea').append("<div class='questionDiv'></div>");
$('#questionArea > :last-child').attr("id", questionDivIdHTML);
Or better, you can rearrange your code like this:
$("<div class='questionDiv'></div>")
.attr("id", questionDivIdHTML)
.appendTo("#questionArea");
#questionArea:last-child selects an element with id = questionArea which is also the last child of its parent
#questionArea > :last-child selects the last child of an element with id = questionArea

Select the option dynamically using Jquery

I am designing a dynamic HTML for Select Option like below:
item += "<td class='ddl' style='width:40%;'>";
item += "<select>"
item += " <option id='list' name='selector' value=" + select + ">" + select + "</option>";
for (var l = 0; l < array.length; l++) {
item += " <option class='ddl' value=" + array[l] + ">" + array[l] + "</option>";
}
item += "</select>";
if ("One"!= '') {
$('#list').val("One");
}
item += "</td>";
The above code creates a dynamic HTML like below:
<select disabled="">
<option select="" value="Please" name="selector" id="list">Please Select</option>
<option value="One" class="ddl">One</option>
<option value="Two" class="ddl">Two</option>
</select>
I want to set the value of the Select to "One" dynamically.
NOTE: The code is not inside document.ready, as I cant keep the code inside ready().
Might be I am assigning the value to the Select before it is revdered on the page. Please suggest me.
You need to call the javaScript to select the value after the dropdown(select) is added to the page. For example if the html is
<div id="myContainer" />
Then the javascript should be like
var item = "";
//Insert your code to create item
item +="<select id='mySelect'>";
item +='<option select="" value="Please" name="selector" id="list">Please Select</option>';
item +='<option value="One" class="ddl">One</option> ';
item +='<option value="Two" class="ddl">Two</option>';
item +='</select>';
$('#myContainer').append(item); //Add to html
//Now the id "mySelect" is available
$('#mySelect').val('One')
I've added a jsFiddle to demonstrate this at http://jsfiddle.net/taleebanwar/n9vCb/
You could also set a selected attribute on the corresponding option tag as you create the select dynamically.
If you are using jQuery then why don't you utilize the library for creating the select, for example, using something like this (Example):
var numbers = ['one', 'two', 'three', 'four', 'five'];
var select = $('<select/>', {id:'list', name:'selector'});
$.each(numbers, function(key, value) {
var text = value[0].toUpperCase() + value.substr(1);
var option = $("<option/>", { class:'ddl', value: value, text: text });
select.append(option);
});
select.val('two').appendTo('body');
I've appended the select into body but you may append it into a td and you can achieve it, give it a try, create the td same way and insert the select in the td and then insert the td in the table. Also you may check this answer.

Filtering next select box's value depending on what is selected in the first select box

I have select boxes in which values are getting appended dynamically thru an array.
Now suppose if i have 4 values in my 1st select box, then i want only 3 values in the 2nd select box excluding the value that has already been selected in the 1st select box.
now there will be 3 values in 2nd select box and if i select a value then the 3rd select box will have only 2 values excluding the one already selected in 2nd select box and so on...
please help on how should i filter
Try this
HTML
<div class="result"></div>
JS
var array = ['first', 'second', 'third'];
var temp;
new_select();
function new_temp() {
temp = "";
temp += '<option value="null"></option>';
array.forEach(function (entry, index) {
temp += '<option value="' + index + '">' + entry + '</option>';
});
}
function new_select() {
if (array.length > 0) {
new_temp();
$('.result').append('<select class="mine_select">' + temp + '</select>');
$(".mine_select").change(function () {
array.splice($(this).val(), 1);
new_select();
});
}
}

Remove item from second dropdown based on selection in First using Javascript

I have four dropdown, and I am manually filling them.
Now I want to add a javacsript that when I select first dropdown option, then in the second third fourth dropdowns, that item or option can be removed.
And same flow goes for second third and fourth and so on.
I am giving my code but till now, it is not working fine.
I am only tring for the first ladder, that is when option in first is selected then item removed from second, third and fourth dropdowns.
function RemoveItems(){
var List1 = document.getElementById("ddlSortField");
var sortList1 = List1.options[List1.selectedIndex].text;
var List2 = document.getElementById("ddlSortField2");
var sortList2 = List2.options[List2.selectedIndex].text;
List2.options.remove(sortList1);
var List3 = document.getElementById("ddlSortField3");
var sortList3 = List3.options[List3.selectedIndex].text;
List3.options.remove(sortList2);
var List4 = document.getElementById("ddlSortField4");
var sortList4 = List4.options[List4.selectedIndex].text;
List4.options.remove(sortList3);
}
In your code:
> function RemoveItems(){
Variable names starting with a capital letter are, by convention, reserved for constructors, so:
function removeItems() {
> var List1 = document.getElementById("ddlSortField");
> var sortList1 = List1.options[List1.selectedIndex].text;
So sortList1 will be a string.
> var List2 = document.getElementById("ddlSortField2");
> var sortList2 = List2.options[List2.selectedIndex].text;
> List2.options.remove(sortList1);
The remove method of the options collection takes a single parameter that is an index of one of the options. You have not shown what the value of sortList1 nor how many options List2 has. Note that the options collection is live, so if you remove an option, the indexes of other options may be adjusted so that they are contiguous from 0 to options.length - 1.
You can use such code : jsFiddle.
Basically, you first bind the change event to each list and when you change the value you hide these elements in all lists after...
I've made a slightly different one than #Muhammad Omair's, this one is a bit more dynamic. Note that this is jQuery
var removeSelection = function(select) {
$('select').filter(':not(#' + select.attr('id') + ')').each(function() {
var index = select.find(':selected').index();
$(this).find('option:eq(' + index + ')').remove();
});
};
$(function() {
$('select').change(function() {
removeSelection($(this));
});
});
And here's a jsfiddle of it http://jsfiddle.net/cA3F9/
Use jQuery to remove option
$(document).ready(function(){
$('#ddlSortField').change(function(){
var index = $("#ddlSortField option:selected").val();
$('#ddlSortField2 option:eq(' + index + ')').remove();
$('#ddlSortField3 option:eq(' + index + ')').remove();
$('#ddlSortField4 option:eq(' + index + ')').remove();
});
});
Note in your html your option value must be same like this:
<select id="ddlSortField">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<select id="ddlSortField1">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>

Categories

Resources