My Javascript code doesn't work in chrome - javascript

I write ajax on my page, to get subcategories in select option, depending on categories option list click. In all browsers it works good, i can see my request, response in browsers console... but in chrome functions even doesn`t call. Dou you know, in what the problem is? Here is my code:
<td>
<span style="color: #898989;">Main categories</span>
<br />
<select style="width: 200px;">
<?foreach ($main_categories as $item){?>
<option onclick="get_sub_cat(<?=$item['id']?>,2);return false;" value="<?=$item['id']?>"><?=$item['title']?></option>
<?}?>
</select>
</td>
<td>
<span style="color: #898989;">Subcategories</span>
<br />
<select name="sub_cat" style="width: 200px;" id="prod_subcat_2">
</select>
</td>
function get_sub_cat(id, select_id){
$.ajax({
type: "POST",
url: "<?=base_url()?>admin/product/get_sub_cat/"+id,
data: "",
success:function (option_list) {
$("#prod_subcat_"+select_id).children().remove();
$('#prod_subcat_'+select_id).append(option_list);
}
});
}

An <option> elements onclick is not universally supported, instead use an event of the parent <select>
$('#theselect').change(function() {
alert( $(this).val() );
});​

1) If you run on local folder and not running on server, then chrome have security reasons not to run these type of javascript calls. There is multiple threads around stack overflow about running localy javascript ajax calls on chrome if thats the case.
2) Try your javascript with simple alert("hey"); to check if javascript is working or its the ajax.
3) If javascript works. Use google "Developer tools" ctrl+shift+i, set breakpoint on your javascript call and check what get passed as variable and wheres the problem.
4) If javascript dont work try this http://support.google.com/chrome/bin/answer.py?hl=en&answer=114662

Try attaching an onchange event handler and getting the selected element from the select element passed into on the event. It probably doesn't make sense to attach event handlers to individual options.

You need to add some quotes :
get_sub_cat(\"<?=$item['id']?>\",2)
you need to send this parameter as a string.
Are you sure your JavaScript is in a <script> tag ? the question doesnt show it
<script>
// your javascript
</script>

Related

Create a checkbox when checked it should show certain input fields & hide other input fields, within a Modal

<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); } else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
I've been attempting to do this with jQuery, but it hasn't been functioning properly, I have also done a thorough amount of research for ways to condense this code. I was trying to condense the statement with a ternary operator. If you could please assist me with a possible solution that would be great! Thanks (Ternary Solution would be amazing)
The issue with your code is that you have mis-matched quotes in the HTML due to the console.log("X") calls in your code that is messing up the attributes of the input element. If you check the console you'll most likely see some errors relating to this.
It's for this reason, amongst many others, that it's considered bad practice to use inline script (or CSS styling for that matter). The other issues are that it's bad for separation of concerns and makes the code harder to read an edit. It's far better practice to attach your event handlers using unobtrusive Javascript, like this:
$('.seasonal-checkbox').change(function() {
$('#ShowIfChecked').toggle(this.checked);
$('#HideIfChecked').toggle(!this.checked);
});
#ShowIfChecked {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" class="seasonal-checkbox" />
<div id="ShowIfChecked">Checked!</div>
<div id="HideIfChecked">Not Checked!</div>
Note the use of the change event over click, so that the event is still fired for user who navigate the web using the keyboard. Also note the simplified logic using toggle() to hide and show the relevant content in a single call to each method which negates the need for an if statement - and by proxy a ternary expression too.
You can change your onclick to a function, because at least for me, it is easier to see whats really going on.
So change
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal"
onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); }
else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
to
<input type="checkbox" runat="server"
name="Seasonal" value="Seasonal" id="isASeasonal" onclick="myFuncton(this)" />
Within your view:
<script>
myFunction(myCheckBox)
{
if(myCheckBox.Checked)
{
console.log('Worky');
$('#ShowIfChecked').show();
$('#HideIfChecked').hide();
}
else
{
$('#HideIfChecked').show(); console.log("No Worky");
}
}
</script>
Now to get the expression/Ternary Solution you want, you can change this script to look like this:
<script>
myFunction(myCheckBox)
{
myCheckBox.Checked ? (console.log('Worky'), $('#ShowIfChecked').show(),
$('#HideIfChecked').hide()); : ($('#HideIfChecked').show(), console.log("No Worky"));
}
</script>
You can find more Info about Ternary Solutions here
We dont write code like this. It fails on every code review.
Do this:
$('#isASeasonal').click(function() { ...});
https://api.jquery.com/click/
Seasonal Address:&nbsp <input type="checkbox" runat="server" clientidmode="Static" name="Seasonal" value="Seasonal" id="isASeasonal"/>
$('#ShowIfChecked').hide(); //Hid What needs to be shown if checked.
$("#isASeasonal").click(function () { //Used Click event on checkBox
($("#isASeasonal").is(':checked')) ? (console.log('worky'), $('#ShowIfChecked').show(), $('#HideIfChecked').hide()) : (console.log('no worky'), $('#HideIfChecked').show(), $('#ShowIfChecked').hide());
What fixed my issue was that in ASP.net I needed to add clientidmode="static" to the div's that I was trying to hide & show. I still don't understand the reason why, I'm currently looking more into it but this is what worked for me but above you can see the majority of the final product with the ternary operator!! Yay.

Adding values to a select box using ajax and organising javascript files

I want to create a page where everything is loaded via ajax calls, so the URL always stays the same. At first the user will be presented with one box with some choices. According to the choice he makes another one will appear and again according to the choice he makes on the second a third will appear. I have successfully created this logic using ajax bit like the following. I am sorry if the code is a bit meshed up, but I am typing the question from a different machine than my code is located, so please be gentle. If you have any problem I will try to provide as much info as I can. So the html
<!DOCTYPE html>
<html>
<head etc....>
<body>
<div class="main-nav">
</div><!--some navigation things here not important-->
<div class=controls>
<div class="select-control1">
<select>
<option selected="selected" value="">Choose one of the following</option>
<!-- adding the django code for this select-->
{% for option in options %}
<option value="{{option.id}}">{{option.name}}</option>
{%endfor%}
</select>
</div>
<div class="select-control2" style="display:none;">
<select>
<option selected="selected" value="">Choose one of the following</option>
</select>
</div>
</div>
</body>
<html>
Also the option1 and 2 in each control1 are prepopulated by a django template for tag (it is a django project).
the ajax calls are triggered on change of each control and the view that is executed from behind sends an array of json_objects
$(".select-control1 select").change(function (){
option = $(this).prop("value");
//Skipping the case where option value is "" for now
$.ajax({
url:'/url/to/view/',
dataType:'json',
type:'GET',
success:onSuccess1
});
});
function onSuccess1(data, status, jqXHR){
$.each(data, function(index, value){
html = "<option value="+value['id']+">"+value['option']+"</option>";
$(".select-control2 select").append(html);
});
$(".select-control2").show();
}
As i said not intrested in error checking or what happens if user checks a different option in select-control1. I do remove them and place the newly gotten ones from the ajax call, just didn't right that right now. My problem are 2 + 1. First of all when the second control is populated with options after the ajax call the "Choose one of the following" option dissappears. Is that the natural behaviour of append?Is there another way?
Second even though i have the selected attribute in the first control in the "Choose one...." option when the page is loaded i don't it won't appear as selected but it will give one of the options loaded from django e.g. option1
Third and final: I am fairly new to ajax and javascript in general, and this kind of programming. I am familiar with procedural languages and can organize them as I want. But Javascript is giving me a hard time. Right now I have a veeery large js file, that will include all ajax and jquery calls of all elements on the page. Is there a way to "modulize" it in a way, to seperate it in different files somehow?Any good links pages books that could give me a guidness?
Thanks in advance!!
This is because of "<option value="+value['id']+>". You missed "
It should be
"<option value="+value['id']+">"+
Or simply try
$(".select-control2").append(new Option(value['option'], value['id']));
If your browser is IE8, the above code won't work. In such cases you have to use something like this,
var opt = new Option(value['option'], value['id']));
$(opt).html(value['option']);
$(".select-control2").append(opt);

is ID of html controls which called by javascript casesensitive or not

i have this control
<input id="btnBackMP" type="button" value="<" onclick="BackGroup('MP') ;"
disabled="disabled" style="background-color: #BF0000; width: 28px;" />
inside backGroup Function i used this Code Line :
document.getElementById('btnback' + Key).disabled = true;
this line works fine on Web Dev but when i published my site on server (iis 7)
this line stop working till i changed it to the following :
document.getElementById('btnBackMP'+ Key).disabled = true;
any one have idea ?
thanks
Have you changed in calling function argument too since before your are passing 'MP' as argument and using as key
<input id="btnBackMP" type="button" value="<" onclick="BackGroup() ;"
disabled="disabled" style="background-color: #BF0000; width: 28px;" />
and why do not you directly change to this line only :-
document.getElementById('btnBackMP').disabled = true;
Element id is case sensitive. The id must be unique but in theory you could use id="elementa" and id="elementA" in the same document to refer on two different nodes.
This is not recommended
Further details on
https://developer.mozilla.org/en-US/docs/DOM/element.id
The id attribute values are case-sensitive by HTML specifications; see e.g. HTML 4.01 on id. They are thus case-sensitive when used in JavaScript too. Note that the document.getElementById method queries the DOM, which must follow HTML conventions here.
So btnbackMP and btnBackMP are distinct id values. Your code seems to have another error too, as pointed out, but this might be just an issue in formulating the question. (I suppose the last code line was meant to have btnBack not btnBackMP.)

Opening Link via New Window from Javascript Select List

I'm not sure what's the issue that is causing that error message when I try debugging with Firebug. Everything looks good to me.
Current Issue:
$("#SlideList option:selected") is null
Select Box Code (abridged) :
<select id="SlideList" name="D1" style="width: 130px;">
<option value = "Numbers.pdf" >Numbers</option>
</select>
<img src="Button.png" onclick="SlidePDFOpen()" />
Javascript:
function SlidePDFOpen() {
window.open($("#SlideList option:selected").val());
}
You are using a jquery selector but you don't have jquery included in the page.
The error you are getting therefore makes sense as the page can't find the function val().
At the very least with jquery you would get an empty string.

Javascript does not work in IE8

The following JavaScript works on IE7 but not on IE8:
onclick=history.back(1) or history.go(-1)
Any suggestions on why this is the case and how to overcome it.
Have you tried:
onclick="history.back()"
with the quotes?
And, responding to your statement that it doesn't work: au contraire, mon ami.
The following two files run fine on my IE8 install, using the files x1.html:
<html><head></head><body>
X1
<hr>
x2
</body></html>
and x2.html:
<html><head></head><body>
X2
<hr>
<button onclick="history.back()">Back!</button>
</body></html>
When I load x1, I can move to x2 with the link, then the button moves back to x1.
This works in all three compatibility modes, ergo it must be a setting on your browser which is affecting this.
One thing I had to do to get this to work was to go to Tools -> Internet Options -> Advanced -> Security and select Allow active content to run in files on My Computer, so it's almost certainly a security setting in your browser which is causing you grief.
i used this and works well :
<asp:Button ID="Back_BTN" runat="server" Text="بازگشت"
onclientclick="javascript:history.back(1);return false;" />
I also had this problem. Never check its also the same on ie7 or not
Code like below cant run on IE8. Can on FF3.5
<select size="2">
<option onclick="alert('hey hey')">Hey hey</option>
<option onclick="alert('a ha')">A Ha</option>
</select>
However, this on work
<select onclick="alert('uh oh')" size="2">
<option>Hey hey</option>
<option>A Ha</option>
</select>
I had the same problem and solved it like this...
<input type="button" value="Back" />
You need to put history.back() into your a href tag and also the onclick event.
Try history.back(), if that doesn't work then try this history.back();return false;
It may be a simple reversal of quotes. Try this
lblmessage.Text += '<br> <u>Back</u>'
instead of this
lblmessage.Text += "<br><a href='#' onclick='history.back(1);'> <u>Back</u></a>"
This isn't the answer, but maybe it will help someone else dig up the real answer... The issue might be related to IE8's compatibility mode. Weird things happen in IE8 based on the DOCTYPE of the web page. If your DOCTYPE is Transitional, IE8 might not properly handle the onclick event.

Categories

Resources