I am using Select2 for dropdown styling from http://ivaynberg.github.io/select2/ .
I have several dropdowns on the page which are styled correctly using the following:
<script>
$(document).ready(function() {
$("#dropdown1").select2();
$("#dropdown2").select2();
});
</script>
Now, I have another option on the page where it allows the user to add as many dropdowns as they want for additional options, the following way:
<img src="images/add.png" title="Add Row" border="0" onclick="addRowToCountryPrice('',''); return false;">
<input type="hidden" name="TotalLinesCountry" id="TotalLinesCountry">
<script>
var arr = new Array();
var ind=0;
function showCountryDrop(name1,sel, param){
var dval="";
dval = "<select name=\"" + name1 + "\" id=\"" + name1 + "\" class=\"countriesclass\">";
dval += "<option value=\"\">Select Country</option>\r\n";
selVal = (sel==0001) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0001\" " + selVal + ">United Kingdom</option>";
selVal = (sel==0002) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0002\" " + selVal + ">United States</option>";
selVal = (sel==0003) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0003\" " + selVal + ">Albania</option>";
selVal = (sel==0004) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0004\" " + selVal + ">Algeria</option>";
dval +="</select>";
return dval;
}
function addRowToCountryPrice(country,price) {
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cellVal = "";
var cellLeft;
var i=0;
arr[ind] = (iteration+1);
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = showCountryDrop("countryDrop_" + ind,country);
cellLeft = row.insertCell(i++);
var price = (price!=0) ? price : "0.00";
cellLeft.innerHTML = "<input type=\"text\" name=\"countryPrice_" + ind + "\" id=\"countryPrice_" + iteration + "\" value = \"" + price + "\" size=\"8\">";
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = "<img src=\"images/delete.png\" title=\"Delete Row\" border=\"0\" onclick=\" removeRowFromTable(" + ind + "); return false;\">";
document.getElementById("TotalLinesCountry").value = (parseInt(ind)+1);
ind++;
}
function removeRowFromTable(src)
{
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
if (arr[src]!="") tbl.deleteRow((arr[src]-1));
arr[src]="";
var counter = 1;
for( i=0; i<arr.length; i++) {
if (arr[i]!="") {
arr[i]= counter;
counter++;
}
}
return false;
}
</script>
While it generates the dropdowns correctly, they are not styled through the class "countriesclass", even if I do a:
$(".countriesclass").select2();
I also tried
dval +="</select>";
$(".countriesclass").select2();
return dval;
And that seems to be PARTIALLY working in a strange way. When I create the first dropdown, it doesn't get styled. When I create another second dropdown, then the first one gets styled but the second one doesn't. It then doesn't let me create further ones and shows an error.
Any ideas how I could get this working?
UPDATE: jsFiddle http://jsfiddle.net/y6af098z/2/
Your call to $('.countriesclass') goes off when the document is ready. But the select has not been added to the document yet, then. So no elements are found.
You should look up the added select after the user has clicked on the plus and you've added the select to the dom.
$('#plus').on('click', function () {
$tr = addRowToCountryPrice('Algeria', 0);
$('.countriesclass', $tr).select2();
});
The second argument $tr tells jquery only to look in the recently added table row, so that you only select the newly added select which is a child of the newly added tr. Not the selects in the other rows.
Like #dreamweiver already noted, you should make better use of jquery when creating the dom elements. That's what jquery is good at. I've updated the jsfiddle to show how you can create the select and table row the jquery way.
DEMO
Instead of using getelementbyId use getelementbyClass and give each dropdown a class, you can only have one getelementbyid.
Hope this helps. if you want i could send you the code for what you require?
The select2 when called was not able to find the dropdown list boxes,because they were added dynamically and hence the those were not visible for the jQuery class selector $(".countriesclass").select2();.
This type of behaviour can be overcome by referencing the selector from the document element, rather than referring the element directly like above. so the new selector should be like this
$(document).find("select.countriesclass").select2();
Also I have done few tunings in your code.
Live demo:
http://jsfiddle.net/dreamweiver/y6af098z/8/
Note: one more thing, when using jQuery lib make sure you make the most of it, don't use raw JS code instead use the jQuery equivalent syntax for the same, which would be simple and easy to use.
Related
I have a dropdown whose options get filled dynamically:
function populateDropdown(dropdownNum) {
// invokeWebService uses $.ajax
json = invokeWebService("GET", "/webservice/dropwdownOptions");
optionsHtml = "";
$.each(json, function(count, jsObj) {
optionValue = jsObj.name
optionsHtml+="<option>" + optionValue + "</option>";
});
var dropdownId = "#NRdropdown_" + dropdownNum;
$(dropdownId).html(optionsHtml);
}
function display(blockNum) {
var url = "/webservice/blocks" + blockNum;
var response = invokeWebService("GET", url);
var replacementHtml = "";
var currBlock = "blah";
$.each(response, function(i, block) {
currName = block.name;
var textfield = "<input type='text' id='blockValue" + block.id +
"'>";
var dropdownMenu = "<select id=\"NRdropdown_" + i +
"\"onClick=\"populateDropDown(" + i +
")\"><option>Existing Blocks</option>"
var submitButton = "<input type='submit' value='UPDATE' id='" +
block.id + "'><br><br>";
replacementHtml = currName + textfield + dropdownMenu + submitButton;
});
$("#main").html(replacementHtml);
}
The javascript function "populateDropdown(dropdownNum)":
Makes the ajax request
Parses the json response for the option values into an html string called optionsHtml
Replaces the inner html of the select element with the option values via:
var dropdownSelector = "#NRdropdown_" + dropdownNum;
$(dropdownSelector).html(optionsHtml)
1) When I click on the dropdown arrow, I STILL see "Existing Blocks".
2) After 1 sec I see the first dynamically generated option UNDERNEATH the "Existing Blocks" option, I don't see the other dynamically generated options.
3) Then I click outside the dropdown and see the dropdwon showing the first dynamically generated value.
4) Finally I click the dropdown arrow again and it works as it should with all the dynamically generated values.
How do I make it work so that:
When the page first loads, the dropdown shows "Existing Blocks".
Once I click the dropdown arrow, the dropdown should show all dynamically generated values without the "Existing Blocks" value.
Thanks!
the dropdown listener should be for onmousedown, not onclick
The first block of code is a working example of what I want the variable select to do. the var Select is there to be a td in the variable tr. the variable tr is used 2 times in this code. once to to append the tr when the table has html and another time when it doesn't have any html. the reason is because if doesn't have html it should append the header and the row with the select element and the rest of the data that's supposed to be on the row and if does have html it should only append the row to prevent repetition of the header. so I would like a nice clean variable named tr that will be append every time the users invokes it. jsfidle if you click on the drop down you could select the item and the new row will appear.
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var select = " <select class = 'select'><option value='volvo>Volvo</option> <option value='saab'>Saab</option> <option value='mercedes'>Mercedes</option> <option value='audi'>Audi</option> </select>"
var tr = "<tr><td>"+ suggestion.value + "</td><td>" +select +"</td></tr>"
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
The thing is I want the select element to be made up dynamically so i tried something and I cant figure out why it wont work. It's not recieving the variable. Am i implementing the varable wrong with the $.each?
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var selectValues = { "3": "2", "2": "1" , "1": "..."};
var select = $.each(selectValues, function(key, value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
var tr = "<tr><td>"+ suggestion.value + "</td><td><select class ='select'>" + select + "</select></td></tr>";
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
},
maxHeight:100,
width:600
});
thanks for your help
Why use object if you use only value?
if you realy don't need key juste create an array :
var selectValues = ["2", "1", "..."];
var value;
var select = selectValues.forEach(function(value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
// or if you want more compatibility
for (var i = 0, len = selectValue.length; i < len; i++) {
value = selectValue[i];
$('.select').append($('<option>', {value: value}).text(value));
});
Edit:
i make some mistake sorry.
first forEach will return nothing so it's can't work.
I test with your fidle. try this (replace by old for loop if you don't want to use map).
var select = selectValues.map(function(value){
return "<option value=" + value + ">" + value + "</option>";
// <option value='volvo>Volvo</option>
}).join('');
first you do not have to append from $('.select') because this dom not exist at this moment
and you can't concate an array in a string like this.
i am trying to create chkbox on click with different name and value and then alerting its value resulting in error "NaN" my script is here,
<script type="text/javascript">
var k=0,j=0;
$(document).ready(function () {
$("#btnAdd").click(function () {
var field = $("#field").val();
k+=1;
var newRow1="<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+DDL_fromProfession +" to "+DDL_ToProfession +"</td></tr>"
+"<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+"<input type='checkbox' name='chkbx_CurrPro'"+k+"'' value='"+k+"'>I currently work here</input>";
alert(k);
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro'"+k+"'']").val()) + 1;
alert(chkvalue);
var checkBoxes = $("input[name=" + chkbx_CurrPro + "]");
$.each(checkBoxes, function() {
if ($(this).attr('checked')){
//do stuff
}
});
var input = "<input name='parameters' id='field' type='text' />";
var input1="<input name='parametersCompany' id='field' type='text'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " +input1 +"</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
</script>
i wanna crete chkbox like,
name = chkbx_CurrPro0 , value = 0
name = chkbx_CurrPro1 , value = 1
name = chkbx_CurrPro2 , value = 2
.
.
.
then i am printing its value resulting in NaN error ?? Hopes for your suggestion
one more thing i wanna do after creating dynamicaally chkbox it will get value of only marked chk box ,
my code here,
var checkBoxes = $("input[name=" + chkbx_CurrPro + "]");
$.each(checkBoxes, function() {
if ($(this).attr('checked')){
//do stuff
}
});
but check all chkbox created at run time
Hopes for Suggestions
Thanks
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro'"+k+"'']").val()) + 1;
I think you have some issues with the quotes here. Try this...
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro"+k+"']").val()) + 1;
EDIT: Looks like youhave the same issue here...
"<input type='checkbox' name='chkbx_CurrPro'"+k+"'' value='"+k+"'>
This will try to make the name chkbx_CurrPro'1' but that is not valid. This should instead be...
"<input type='checkbox' name='chkbx_CurrPro"+k+"' value='"+k+"'>
Edited Again :
I see another issue here, you are trying to get the value of the checkbox before the checkbox has actually been added to the dom. You have added it to the string, but that is just a string of text when you call parseInt, not a part of the page. Move the parseInt line to below your append lines, near the bottom.
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here
feel like im coming here way too often to ask questions but yet again I am stuck. I am attempting to select a textarea and allow myself to edit the text in another textarea, which works fine using textboxs but not with textareas. Every time I click on the div container I am getting an undefined result when looking for the textarea. Below is the code.
jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id') should be returning textbox1(or similar) but instead just returns undefined.
I have tried .find(':textarea'),.find('textarea'),.find(text,textArea),.find(':input') and quite a few others that I have found through google but all of them return undefined and I have no idea why. A demo can be found here, http://jsfiddle.net/xYwaw/. Thanks in advance for any help guys, it is appreciated.
EDIT: Below is the code for a very similar example I am using. This does what I want to do but with textboxs instead of textareas.
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
First up remove the second parameter, 'div', from the first line:
$(".textAreaContainer").live('click','div', function(){
...to make it:
$(".textAreaContainer").live('click', function(){
Then change:
var t = $('#' + divID ).find(':input');
...to:
var t = $(this).find(':input');
Because you already know that this is the container so there's no need to select it again by id. Also the id attributes that you're assigning to your textarea containers have a space in them, which is invalid and results in your original code trying to select the element with '#textAreaContainer 0' which actually looks for a 0 tag that is a descendant of #textAreaContainer. So fixing the code that creates the elements to remove that space in the id is both a good idea in general and an alternative way of fixing this problem.