Specific javascript code only working with alert statement - javascript

So I have a drop down menu that's supposed to be populated by a Json object value. The code reads like this:
$("#sport").val(model.SportId);
Well, when I load the page, it doesn't work. The drop down list defaults to the default "None Selected" option. So I do a ghetto debug and I put an alert on model.SportId to see what's up.
And when I refresh the page...it works. The only thing that I did was
alert(model.SportId);
It brings up a pop up window that says "1" and then the drop down menu value goes to the option 'Major League Baseball' (which is the text of that option value). That's it. That's the only thing I changed. Putting the alert before that first line of code. If I put the alert after the code, it doesn't work. I have no idea why this is.
The viewmodel that the Json object is derived from has SportId as a nullable int. Could that have anything to do with it?
Edit:
Okay, so in my razor view, this is the javascript I have:
<script type="text/javascript">
$(document).ready(function () {
var model=#Html.Raw(Json.Encode(Model.Title));
var read=#Html.Raw(Json.Encode(Model));
var sportsurl='#Url.Action("GetSports", "Titles")';
var sportsteamsurl='#Url.Action("GetSportsTeams", "Titles")';
TitleBasicEdit(model, read, sportsurl, sportsteamsurl);
});
And the javascript function titlebasicedit is:
function TitleBasicEdit(model, url, read, backurl, seasonsurl, autocompleteurl, urlforward, sportsurl, sportsteamsurl) {
if ((model.TitleTypeId == 3) || (model.TitleTypeId == 8)) {
GetSports(sportsurl);
SportsDependency(sportsteamsurl);
alert(model.SportId);
$("#sport").val(model.SportId);
$("#sport").change();
$("#hometeam").val(model.HomeSportTeamId);
$("#awayteam").val(model.AwaySportTeamId);
}

It could be an issue related to an asynchronous task you perform while populating your options (like an ajax request). That could be the reason why the alert() works: it stops the execution oj javascript so that the task has enough time to be completed (anyway a link may be really appreciated).
edit: the GetSports() function could be that task;

I wonder if it is because model.SportId is a typeof === 'number' ..? Have you tried this? I don't know why it would work though, because jQuery should be smart enough to handle this:
$("#sport").val(model.SportId+'');
Also, try this:
alert($("#sport").length);
$("#sport").val(model.SportId);
alert($("#sport").length);
It could be that your javascript is executing before the HTML loads. The alert() may give it just enough time to load.

Related

Semantic UI dropdown lags entire ui when setting values

I have a large select with about ~1500 items in it. Whenever i call this code
$('#multi-select').dropdown('set exactly', ['my value']);
to set its value, the entire UI locks up and lags. Now I know this is due to the large dropdown (1500 items) but I'd like to know if there is a way to keep that many items without flushing the user experience down the toilet.
I've put together an example below. You can try clicking the button once, or multiple times consecutively to see the browser choke.
http://jsfiddle.net/qhy9do4w/1/
I've looked in the code and profiled the click. Somewhere in its bowels Semantic fires a lot of events and most of the lag time is taken by module.trigger something. Inside the code looks like this:
trigger: {
change: function() {
var
events = document.createEvent('HTMLEvents'),
inputElement = $input[0]
;
if(inputElement) {
module.verbose('Triggering native change event');
events.initEvent('change', true, false);
inputElement.dispatchEvent(events);
}
}
}
I don't see any way to disable the event handling part.
I had a look into the semantic.js code for the dropdown set exactly and it is quite something: https://github.com/Semantic-Org/Semantic-UI/blob/74fea12e1fd548cb870872ba5ed59f5acdcc57ba/dist/components/dropdown.js#L2219:L2295
You could try figure if the code is slow somewere or wether you can do any sort of shortcut.
But, that is hard and you might want to think about an alernative like a search.
Our solution was to simply cache the contents and only put in a selected subset of options into the drop down itself.

Change hard coded JS variable value

I am using a 3rd party app and they have a JS variable hard coded into their HTML that I need to change / update with Javascript OR jQuery, both are available to use.
The 3rd party app has variables hard coded into the page:
<script type="text/javascript" charset="utf-8">
var order_poNumber = "";
</script>
Which gets updated when a user selects a value from a dropdown (my dropdown, not 3rd party):
<script type="text/javascript" charset="utf-8">
var order_poNumber = "32380080-64060";
</script>
But the issue is that the value sticks for some reason. If you go to another page and come back (not using the back button, but by going to a different page then clicking a link to return to the order page where this issue is happening) the value is still set to 32380080-64060 but I need it to be blank as it originally was.
I've tried:
function resetPO(){
order_poNumber = "";
}
window.onload = resetPO();
And a few other variations of that, but it won't work.
I have to do the JS from an external JS file BTW.
Any ideas?
I am looking for a way to overwrite the value that is stored in the variable order_poNumber in the JS script block that is hard coded in the HTML. Ideally I want some kind of late or even delayed JS to come in and overwrite the value once the page has loaded. There are a lot of steps in how that number gets there once selected from the dropdown (AJAX, ActiveX, JS, jQuery, and a mix of 3rd party app and my own codes and functions) which took a lot of work to get working properly so I don't want to mess with all of that anymore.
The browser back button works differently than an initial page load. You can use jquery-address to add a listener to page changes (including ones from navigational arrows):
$.address.change(function(e) {
resetPO();
});
http://github.com/asual/jquery-address
Heres something I would try, just to see if it could work. We'll ask the browser to keep resetting the value until its actually reset. It does need to be executed after any script that sets the value in the first place, so maybe jQuery's ready() function is more useful than window.onload (which may already be in use by something else). Don't forget to put it before the ending </body> tag to make sure its the last thing being executed or loaded.
window.onload = function(){
var resetValueInterval = setInterval(function(){
order_poNumber = "";
if(order_poNumber == ""){
clearInterval(resetValueInterval);
}
},100);
}
You could also, instead of checking if it is set, stop checking when the value gets set. This could be never and use a lot more resources, but its always worth a try. Of course, if you reduce the amount of time between each iteration it becomes more reasonable. Not the most elegant way around the problem, but it might work.
window.onload = function(){
var resetValueInterval = setInterval(function(){
order_poNumber = "";
},100);
document.getElementById(/* order_poNumber-dropdown-id */).addEventListener("mousedown", function(){
clearInterval(resetValueInterval);
}, false);
}

Problems Implementing a Premade Javascript

I would first like to state that I started learning HTML 5 days ago, and therefore I am very new to everything.
I am trying to implement the code given here: http://jsfiddle.net/NFXzn/9/.
But for some reason the dropdown menu is blank. I have uploaded my code here: http://gbrowse2014.biology.gatech.edu/viru.html
Since I did not make the code, I am assuming the problems lies with how I implemented the code (specifically the javascript). I have narrowed the problem down to one particular function:
$.each(g_Vehicle, function(index) {
var iYear = g_Vehicle[index].Year;
if ($.inArray(iYear, g_YearsArray) == -1) {
g_YearsArray.push(iYear);
}
});
I am using firefox, and I have gone through www.w3schools.com to look for implementation tips, but I have not corrected the problem.
On a sidenote, does anyone know how to change the code to use the dropdown-checkboxes instead of the dropboxes?
That loop is working fine. The problem is that you're running the code before your select is loaded, so nothing is being appended to the page. Either wrap your code in $(document).ready( function() { ... });, or move your <script> blocks to the bottom of the page (after the HTML has completely loaded).
http://learn.jquery.com/using-jquery-core/document-ready/
(On the top-left corner of the jsFiddle page, you'll see a dropdown which displays onLoad -- which is automatically doing that job for you. Your page as it stands is the equivalent of No wrap - in <head> -- not what you want.)

How can I pass parameters from the element clicked, when right clicking an element in a web page?

I have a table, with a lot of elements. It is a calendar with events, and every event has it's own ID number, as well as one of three different categories, let's call them A, B and C.
Now for styling reasons, the categories are also implemented CSS-classes, which has the same names.
I ahve searched a bit on how to implement a "right-click-listener" with javascript/JQuery. I tried a couple of different solutions, before setteling on a override of the contextmenu-function, that the right button usually fires. I have also been able to differ between the categories, by passing parameters, that the contextmenu should only be overridden when elements of A, B and C are clicked. The following code works perfectly:
$(document).on("contextmenu", (".A, .B"), function(e) {
$.colorbox({width:"554px", height:"480px", iframe:true, href:"myurl"});
return false;
});
$(document).on("contextmenu", (".C"), function(e) {
$.colorbox({href:"myurl"});
return false;
});
The colorbox, if not familiar with it, is just a popup, implemented as an editor of my calendarevents. However I wish to pass on the source of the click's identification number, and I have not been able to find out how. These ID's are unique.
So:
Can I pass parameters through this function?
If so, how?
If not, or if this overriding contextmenu is a bad way of doing it, how should it be done?
If any relevance at all, this is a part of a Java web app. I am using jstl and jsp when coding.
Thank you.
EDIT:
here are two functions. The top is a changelistener I use on some checkboxes, and they work. The bottom is the overridden contextmenu, but it does not work. Somehow it seems that the $function breaks out of the parent function, and ignores everything after. The return statement does not work, and the contextmenu appears.
$(document).ready(
function() {
$('.toggle').change(function() {
var id = this.value;
$('.' + id).toggle(this.checked);
});
});
$(document).ready(
function(){
$(".A, .B").contextmenu(function() {
var id = $(this).Attr("class");
alert(id);
return false;
});
});
EDIT 2:
In other words, I just solved my own problem. Even so, I only kinda answered my own question. I have figured out how to pass at least a single parameter, but it still need to be one of the set parameters of a given html-element, this time, the . I set my desired identification number, as the elements id, and retrieved the value like this:
$(document).ready(
function(){
$(".A, .B").contextmenu(function() {
var id = this.id;
alert(id);
return false;
});
});
Still, I feel this is a clunky way of implementing a "onrightclicklistener", especially when compared to how I am used to do it in SWING. I'll leave the question unanswered, In case someone know of a better solution.
Five years later, i think it is time I answered my own question.
//my standard settings object, only relevant to colorbox
var popup_settings = {
opacity : "0.6",
width : "554px",
height : "640px",
iframe : true
}
//executes when the document has finished loading
$(document).ready(function(){
//ovverrides right click function
$(".A, .B").contextmenu(function() {
var id = $(this).attr("data-value");
var settings.href = "myURL?id=" +id; //adds the parameter directly in the URL
$.colorbox(calendarelement_editor_settings);
return false;
});
});
This is obviously a bit specific for a colorbox setup, but a lot of the code is relevant for any setup. When you bind a function to an event through jquery, like I do with contextmenu here, the specific element clicked is accessible through this. All jquery functions can be used on the element through $(this).anythingInTheAPI(); Like getting the attribute data-value, in my case.
any other function, like $(this).hide(), is also available.
Now that I have the attribute i want to pass, the next step is to include it in the request for the new page. This popup opens up a separate page inside a modal container. There are many ways to do this, but the simplest one, is to include the parameter directly as a part of the URL, and implement a back end that expects that. To include parameters in an url, you write
myURL?firstName=firstValue&SecondName=SecondValue
The question mark signals that parameters are following. the & is a seperator between parameters.

Load a second div when a button is clicked

The purpose of this code was to populate a div from a PHP file when a button is clicked.
Also to pre populate a div when page loads - I have completed this task.
Now I want to load a second div at the same time and I'm unsure how to go about this.
function loadpage(clicked_id) {
if (clicked_id != 0 || clicked_id != null || clicked_id !="") {
$("#Table").load("marshfight1.php?action=fight&id="+ clicked_id);
$("#mobs").load("marshtab.php");
}
}
$(document).ready(function() {
// initial
$('#mobs').load('marshtab.php');
});
Echo "<div id=Table></div>";
Echo "<div id=mobs></div>";
$selem = mysql_query("SELECT * FROM senemies WHERE userid='$playerinfo[id]' && arena='10'");
while($enem = mysql_fetch_array($selem)) {
Echo "<button><type=button id=\"$enem[id]\" onclick=\"loadpage(this.id)\" name=\"$enem[id]\">$enem[name]<br>Level: $enem[level]<br> HP: $enem[hp]</a></button>";
}
Everything works fine except for the second .load to update #mobs.
The problem appears to be the inclusion of PHP in your javascript. Remember that though PHP will throw a compile error, IE will do its best and FF will do its best up to the point of the error then very quietly quit. Thus it will appear to be working but actually half your code never gets executed. ctrl-shift-k in FF will give you a rundown of errors.
What you need is ajax. This is easy to implement in both jquery and 'straight' javascript.
Forgive me if you already know this, but others use this forum so a brief summary of the process would be:
Button is clicked triggering JS onclick function.
onclick function sends appropriate data (which button for instance and/or usernumber etc) to php file.
onclick function puts whatever the php returns in the div as desired.
You need to get your js and php organised and separated.
A good overview and basic tutorial can be found at http://www.w3schools.com/ajax/

Categories