So i have a page that has a couple of jQuery plugins. Among other things i have the multiselect toolbar, a pretty sweet plugin. problem is that when i load up the page in internet explorer the page breaks. i've been able to determine that the problem occurs when i try to set some attributes to some elements that i have dynamically generated.
here is the code for generating the elements:
$.ajax({
url: '#Url.Content("~")' + 'Ticket/GetTvrtke',
async: false,
success: function (data) {
document.getElementById("header_tvrtka_holder").innerHTML = data;
var tvrtke = data.split(", ");
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("KlijentMultiSelect").innerHTML +=
"<option value=\"" + tvrtke[i] + "\" id=\"" + tvrtke[i] + "\" >" + tvrtke[i] + "</option>";
}
$("#KlijentMultiSelect").multiselect({
selectedText: "",
height: 125,
minWidth: 650,
noneSelectedText: 'Izaberite željene tvrtke:'
});
}
});
the function gets the correct data and generates the options, and then i activate the plugin to render the new dropdown menu with checkboxes.
problem is that afterwards i have this code:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("ui-multiselect-" + tvrtke[i]).checked = true;
}
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("ui-multiselect-" + tvrtke[i]).setAttribute("onclick", "ChangeTextKlijent()");
}
here i am trying to set the checkbox values to true and add an on click event to the input element, but then visual studio sends me the error message from the title. in firefox, everything works great but IE is a whole different story.
anyone know how to fix this?
I switched so that my code looks like this:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
$.each(tvrtke, function (index, value) {
$("#KlijentMultiSelect").append("<option value=\"" + value + "\" id=\"" + value + "\" >" + value + "</option>");
});
and now it works.
Related
Let's say I have an array of links like this:
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
And a bunch of boxes generated in the following way:
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke luke-" + i + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
I then want to iterate through this array to open a specific link when a box is clicked.
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(){
window.open(playlist[i], "_blank");
})
}
That doesn't seem to work at all, however the example below does exactly what I want.
$(".luke-1").click(function(){
window.open(playlist[1], "_blank");
})
$(".luke-2").click(function(){
window.open(playlist[2], "_blank");
})
$(".luke-3").click(function(){
window.open(playlist[3], "_blank");
})
$(".luke-4").click(function(){
window.open(playlist[4], "_blank");
})
$(".luke-5").click(function(){
window.open(playlist[5], "_blank");
})
So this works, but it's a pain in the ass to setup as I want to have 25 boxes in total and this solution offers little to no flexibility if I want to increase or decrease that amount at a later time. What am I doing wrong with the for-loop that's causing issues here?
If I use
console.log(playlist[i]);
inside of the for-loop, it simply returns "undefined" regardless of what box I click in case that helps.
You can do this much easier and simpler using a data attribute.
HTML
<div class="container"></div>
Javascript/jQuery
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke' data-url='" + playlist[i] + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
$('.luke').click(function() {
window.open($(this).data('url'));
});
Demo Here
You are not doing right.
EXAMPLE FIDDLE
var playlist = [
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
var container = $("#container");
for(var i = 1; i < 5; i++) {
container.append('<div class="luke" db-id="'+ i + '"><h3 class="nummer">Luke ' + i + '</h3></div>');
}
$(".luke").click(function(i){
window.open(playlist[$(this).attr('db-id')], "_blank");
});
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(i){
window.open(playlist[i], "_blank");
})
}
The click event will launch your function only inside the scope of the loop. This means that once the loop have finished, ( and counting from 0 to 5 is insanely fast for your computer ) there's no more function attached to your click event. In other terms, as long as i < 5, your click function will work as you expect, but after that, the click event will no longer call the function you created.
One solution could to be attach a function to the onclick attribute in the HTML like this :
for(var i = 1; i < 5; i++) {
$('<div/>', {
'class': 'luke luke-' + i,
'click': yourFunction(i)
}).appendTo(${'.container'});
$('<h3/>', {
'class':'nummer',
'html': 'Luke' + i
}).appendTo(${'.luke-'+i})
}
and then write a function like this :
function yourFunction(index){
window.open(playlist[index], "_blank");
}
Simple way by using Hyperlink
hyperlinks
Demo Here
I have a list of tables.
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" key="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
And tables have two color, when it is busy or not busy. If there is current_order in table, it shows busy. What I want to do is that when a user clicks empty table, it gets table_id, changes class from table_btn to table_selected and add keyof div, which is current_order.
I use phoenix-framework for my backend, so when a user clicks an empty table, it creates order and passes value of clicked table_id and created order_id. But I am not sure that how can I get a table by value of table div and put key into div...
Can anyone give me advice for this??
So as you tagged Jquery, i'm gonna post this. Change key for ID and you can do the following. I would then wrap the add table and remove table in functions where u pass in the data[i].current_order into and use that.
Edited based on user feeback, not tested
/*If you are not comfortable using the variable 'This',
you can just pass in the id of target table and
change the syntax to $("#"+targetTable)*/
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" id="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
// On Click set table to busy
$(".table_btn").click(function(){
addTable($(this).val(), $(this));
});
// Add table function
function addTable(tableId, targetTable){
$.ajax({
url: "YourBackEndHere",
data: tableID
cache: false,
success: function(html){
$(targetTable).removeClass("table_btn");
$(targetTable).addClass("table_selected");
$(targetTable).attr("id", data[i].current_order);
}
});
}
// On click set table to empty
$(".table_selected").click(function(){
removeTable($(this).val(), $(this));
});
// Remove table function
function removeTable(tableId, targetTable){
$.ajax({
data: tableId
url: "YourBackEndHere",
cache: false,
success: function(html){
$(targetTable).removeClass("table_selected");
$(targetTable).addClass("table_btn");
$(targetTable).attr("id", "");
});
}
});
}
I'm having a problem with a script that is part borrowed and part my own, it is javascript and php that populates two dropdown lists, with options in the second being dependent on what the user selects in the first. For some reason, it won't load the options in the second dropdown when the initial option is selected in the first, either on page load or if it is selected manually (if the options were 'a, b, c, d, e...etc', it won't load anything for 'a').
I think it might be something to do with the javascript document ready function, but I'm afraid I know very little about javascript. This is the javascript code:
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctProxy").change();
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});
Change event is only fired, when selection is changed - not when filled ;-)
Try adding $("#slctOutcome").trigger("change"); at pre-last line
Have fun :-)
Try the below. Second function wasn't being called in first function.
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctOutcome").change(); //<-Here
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});
I'm trying to get the values of my dynamically filled select list in a global variable. This is how I get and fill the select list:
My dropdown.js script:
$(document).ready(function () {
$("#slctTable").change(function()
{
$.getJSON("dropdown_code/get_fields.php?table=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#slctField").html("");
$("#slctField").append(options);
$("#slctField").change();
});
});
});
So after this I tryed this code in my main.js scgript to get the values of the select lists:
$('#slctField > option').each(function(){
console.log(this.value); // Use this.value to get the value of the option
});
var options = [];
$('#slctField > option').each(function(){
options.push(this.value);
});
console.log(options);
But when I run my scripts this the result I get back:
But when I copy and paste the code in firebug and run it. I get the result i want.So I think the select lists aren't filled yet when i try to get the values. But I'm stuck on this for a long time and I don't know what to do at the moment.
Because getJSON is asynchronous, to solve your problem you can trigger a custom event when the select is completed (at the end of getJSON success).
In my example I used this slctFieldFilled new event.
This is a different approach. Another possible solution can be based on callbacks: at the end of an asynchronous function execute the callback function, like the getJSON does.
My snippet:
$(function () {
$.getJSON('https://api.github.com/users', success = function (data) {
var options = '';
for (var i = 0; i < data.length; i++) {
options += "<option value='" + data[i].id + "'>" + data[i].id + "</option>";
}
$("#slctTable").append(options);
$("#slctTable").change();
});
$("#slctTable").on('change', function(e) {
var par1 = $(this).val();
$.getJSON("https://api.github.com/users", success = function(data) {
var options = "";
for(var i = 0; i < data.length; i++) {
options += "<option value='" + data[i].id + "'>" + data[i].id + "</option>";
}
$("#slctField").html("");
$("#slctField").append(options);
$("#slctField").change();
//
// Now, the slctField is filled, so trigger your custom event
//
$('#slctField').trigger('slctFieldFilled', options);
});
});
$("#slctField").change(function() {
var par1 = $(slctTable).val();
var par2 = $(slctField).val();
$.getJSON("https://api.github.com/users", success = function(data) {
var options = "";
for(var i = 0; i < data.length; i++) {
options += "<option value='" + data[i].id + "'>" + data[i].id + "</option>";
}
$("#slctAttribute").html("");
$("#slctAttribute").append(options);
$("#slctAttribute").change();
});
});
// listen on custom event...
$('#slctField').on('slctFieldFilled', function(e, optionVariable) {
var options = [];
$(optionVariable).each(function(index, element){
options.push(this.value);
});
$('#log').text(options);
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<select id="slctTable"></select>
<select id="slctField"></select>
<select id="slctAttribute"></select>
<p id="log"></p>
You're very correct! Your GET is asynchronous and will likely complete long after your main.js code has finished executing. You'll want to make sure your modifications to the global variable is tied to your callbacks in some way so its guaranteed to run afterwards.
var options = [];
$("#slctField").change(function()
{
$.getJSON("dropdown_code/get_attributes.php?table=" + $(slctTable).val() ,"field=" + $(slctField).val() , success = function(data)
{
...
//Option 1: Append the values inside your callback.
//Use window.options because you have another local variable options(window.XX calls any global XX)
for(var i = 0; i < data.length; i++)
{
...
window.options.push(data[i]);
}
//Option 2: Basically the same thing as 1, call a function that does the same thing at the end of your callback
populateOptions();
});
});
function populateOptions(){
$('#slctField > option').each(function(){
options.push(this.value);
});
}
There's plenty of other ways to do it as well as long as you guarantee it executes after your GET. If you have any questions, post a comment. Be careful about the scope of options since you have multiple variables named options(or consider different names so that you can't be confused later on!).
I have a jQuery extension method to create custom animated drop-down select lists based on this answer. Using this method on a page with one drop-down works perfectly:
The extension method is as follows:
$.fn.extend({
slidingSelect: function (options) {
var select = $(this);
var selector = select.selector;
var width = $(selector).width();
var selectedValue = select.val();
if (selectedValue === "undefined")
selectedValue = select.find("option:first").val();
console.log($(selector + " option:selected").text());
var divToggle = $("<div class='SelectorToggle SelectorToggle-defualt'>" + $(selector + " option:selected").text() + "<button style='float: right; width: 20px' id='ddlImgBtn'></button></div>")
.attr({ id: select.attr("id") + "Toggle" })
.css({ width: select.width() + 20 })
.click(function () {
$(selector + "Toggle").toggleClass("SelectorToggle-defualt");
$(selector + "Toggle").toggleClass("SelectorToggle-pressed");
$(selector).slideToggle("fast");
}).insertBefore(select);
var optionCount = $(selector + " option").length;
if (optionCount < 5) {
select.attr("size", optionCount);
}
else {
select.attr("size", 5);
}
select.addClass("drop-down-selector");
$(selector).css({ 'width': select.width() + 20, 'position': 'absolute', "z-index": '9999' });
select.change(function () {
divToggle.html($(selector + " option:selected").text() + "<button style='float: right; width: 20px' id='ddlImgBtn'></button>");
$(selector + "Toggle").toggleClass("SelectorToggle-defualt");
$(selector + "Toggle").toggleClass("SelectorToggle-pressed");
$(selector).slideToggle("fast");
});
}
});
I call it as follows:
$("#LanguageSelector").hide().slidingSelect();
I am however having endless issues getting it to work on a page with multiple drop-downs. My dropdowns are dynamically created as part of a DataTable solution with server-side processing. The drop-downs in the footer:
If i call the following:
$("select").hide().slidingSelect();
then somehow all drop-downs on the page create the custom control:
if I attempt to call the extension method on each element individually:
$("select").hide().each(function(index) {
$(this).slidingSelect();
});
I also tried to call the extension method individually as the drop-downs are created (to just one of them):
$('#RelatedCasesGrid tfoot th').each(function () {
var col = $(this).html();
//..........
else if (col === "ComplaintTypeName") {
$(this).html(GetDropDownInput(col, caseId));
var element = $(this).find("select");
element.hide().slidingSelect();
}
The method GetDropDownInput(col, caseId) creates the drop-downs as follows:
function GetDropDownInput(col, id) {
var control;
$.ajax({
method: "GET",
dataType: "json",
async: false,
url: "/OATS/Api/GetColumnItems/" + id + "?column=" + col
}).done(function (data) {
control = "<select id='selector' class='table-filter-input-drop-down-list'><option value='' disabled selected>Filter by</option>"
for (var i = 0; i < data.length; i++) {
control += "<option col-type=" + data[i].Type + " value='" + data[i].Name + "'";
if (data[i].Selected) {
control += "selected='selected'";
}
control += ">" + data[i].Name + "</option>";
}
control += "</select>";
});
return control;
}
The result of this:
From: http://www.w3schools.com
The id attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
But your ajax method create the same id for all selects: "selector". Change this method to create unique id (value of 'col' parameter seems be ok for this purpose), and then call:
$("#your_unique_id").hide().slidingSelect();