i'm using 2 dropdowns where the second gets populated from the first choice.
My problem is that i'm not getting the value from the first dropdown.
What i get is [object Object].
Here's the javascript and php code:
Thanks.
Javascript:
function getState(){
$("#selectestate").bind("change",function(){
$("#selectcity").load("results/ajaxcity", {stat: $(this).val()} ); //This is where the problem is
alert({stat: $(this).val()});//Shows [object Object]
});
return false;
}
PHP:
$curstat=$this -> input -> post('state'); //current selected state in first dropdown
<tr>
<?php $js = 'id="selectstate" onChange="getState();"';?>
<td><h3> State: </h3></td>
<td id="selectestate"><?php echo form_dropdown('state', $stat, $curstat, $js);?></td>
</tr>
<tr>
<td><h3> City: </h3></td>
<td id="selectcity"><?php echo form_dropdown('city', $cit);?></td>
</tr>
You need to alter this code:
$("#selectestate").bind("change",function(){
to this:
$("#selectestate select").bind("change",function(){
You are asking for the value of the <td id="selectstate"> ... which is of course null. #selectstate select loads the actual <select> element that you are looking for, which will then enable you to get its value.
You will also want to change $("#selectcity") to $("#selectcity select") to avoid the same problem in your anonymous function.
Finally, your alert is behaving as expected. {} defines an object in Javascript. So you are alerting an object containing a single attribute. Just alert($(this).val());// Should show the value
If it still fails it's because either:
A) Your URL is wrong
or
B) There is something wrong with the php function called by results/ajaxcity
EDIT:
Smacks head: I should have caught this. In your code you have this function:
1. function getState(){
2. $("#selectestate select").bind("change",function(){
3.
4. $("#selectcity select").load("results/ajaxcity", {stat: $(this).val()} );
5. alert($(this).val());
6. });
7. return false;
8. }
Your generated HTML looks something like this:
<select name="state" id="selectstate" onChange="getState();">
THE PROBLEM: When you use the <select> for the first time your function is called and jQuery binds an anonymous function to the change event for select (line #2) that will be executed every time the change event fires from this select from now on. Every time you select the dropdown a new anonymous function is bound by line #2 and all of the functions that are currently bound to the dropdown are executed. (So if you use the dropdown N times the "change" function will fire N-1 times.)
THE SOLUTION: Use $(document).ready() to bind your function. Your restructured code will look like this:
<script type="text/javascript">
function getState(element){
$("#selectcity select").load("results/ajaxcity", {stat: $(element).val()} );
alert($(element).val());
return false;
}
</script>
//... snip ...
<?php $js = 'id="selectstate"';?>
//... snip ...
<script type="text/javascript">
$(document).ready(function() {
$("#selectestate select").bind("change", getState);
});
</script>
There is no value for td element, which you are accessing in "#selectestate" selector. Instead of {stat: $(this).val()} you should find inner select element {stat: $(this).find("select").val()}
You're loading the .val() of a <td> element ($(this), inside your handler for a TD). You need to get the id of the <select> tag.
If you really can't find the ID (or codeigniter doesn't set it.. impossible to tell from your example since form_dropdown() is creating it), then instead of $(this).val() you could try $('select',this).val() which will find the value of the first <select> tag within the TD.
Also in your debugging, {stat: $(this).val()} is an object, so of course that's what alert() shows you. Try using firebug, and then change alert() to console.log() -- the firebug console will show you the full object. You could also simply do alert($(this).val()) -- though realize of course that it will be wrong due to the first paragraph above.
Related
We have the following script which runs on a change to a drop-down - updates the price based on the currency code chosen. This basically gets the value of the drop-down and updates the priceamm and preicecurr fields within the text on the page.
<script>
function run() {
var f = document.getElementById("dropPrice");
priceamm.innerHTML = f.options[f.selectedIndex].value;
var e = document.getElementById("dropPrice");
pricecurr.innerHTML = e.options[e.selectedIndex].text;
}
HTML
<select id="dropPrice" onchange="run()" class="fa-select">
<option value = "a">aaa</option>
<option value = "b">bbb</option>
Question
Now, we would also like to load the drop-down to one of the options (selected) when loading the page (onload). We are able to populate the variables in the text but not the drop-down to show option bbb. In php this is quite easy but we are a bit lost with javascript. We tried something on these lines onload but does not work:
document.getElementById("dropPrice").value = "<?php echo $geo_price ;?>";
With jQuery this is probably easier but once again no luck:
window.onload = function() {
jQuery(document).ready(function($){
document.getElementById('dropPrice').find('option[value=<?php echo $geo_price ;?>]').attr('selected','selected');
});
}
Any help is appreciated. Thanks
The jQuery selector part is incorrect. You are mixing plain JS with jQuery. When you call document.getElementById('dropPrice') a regular DOM element is returned, but then you call find which is a jQuery method to be used on a jQuery element. So, you either need to wrap the first part to return a jQuery element like so:
$(document.getElementById('dropPrice'))
.find('option[value="b"]').attr('selected', true);
Or, select it via jQuery in the first place like:
$('#dropPrice [value="b"]');
However, your first example:
document.getElementById("dropPrice").value = "b";
should work. That makes me wonder if the value that is being echoed by PHP is correct and/or if there are other JS errors being thrown that would cause that code not to run.
I have a Datepicker for Bootstrap and I am having an issue to run a function called "listCampaignsFiltered(search, type, from, 'dataTable')" that filters the results once I click on any date from the calendar. Here is the code:
Html
<div id="showfrom">
<label for="from" class="filter">From:
<input type="text" class="filter" value="01/01/2014" id="from"/>
</label>
</div>
Js
$(document).ready(function(){
$('#showbrand input').val(01/01/2014).click(listCampaignsFiltered);
});
The proper form would be:
$('#showbrand input').val('01/01/2014').on('click', function() {
listCampaignsFiltered(...params....)
});
The call val(01/01/2014) would set the value to 1 divided by 1 divided by 2014. You are missing quotes.
Are you sure you always want to set the date back to 01/01/2014? If so use the commented out line instead of the line bellow it.
Next listCampaignsFiltered has be be defined and without error. I am assuming it works and you've tested it independently of the listner.
Next, to pass the values into it, you need wrap the function in an lambda/anonymous function.
I am also assuming that the values for function are all in inputs with the ids matching the parameters you gave in your post.
Here is what you end up with, with those changes:
$(document).ready(function()
{
/*$('#showbrand input').val('01/01/2014').click(function()*/
$('#showbrand input').click(function()
{
listCampaignsFiltered
(
$('#search').val(),
$('#type').val(),
$('#from').val(),
'dateTable'
);
});
});
may be this is what you intended
$(document).ready(function(){
$('#showbrand input').val('01/01/2014').on('click', function()
listCampaignsFiltered(param1,param2,param3,param4);
});
});
jsfiddle.net/JixunMoe/29wBy/
Not sure if that's what you want, but the callback works as expected (for me).
I have a struts tag like this
<s:select label="Select Item" name="select3ph3meter1" id="select3ph3meter1"
headerKey="0" headerValue="-- Please Select --" list="meterHeaderList"
required="true" onchange="show_3ph3meter1(this.value)" />
The problem is it is not calling the above function on change event. It works when I change the code to this:
... onchange="alert('calling')"
I can't understand what's happening here.
Here is the JavaScript function:
function show_3ph3meter1(select3ph3meter1) {
$("#3ph3meter1").load("meterFiller3p31.action",{select3ph3meter1:select3ph3meter1});
}
function show_depotReceipts(selectrecitem) {
$("#recQuantity").load("depotRecQ.action",{selectrecitem:selectrecitem});
$("#recRange").load("depotRecRange.action",{selectrecitem:selectrecitem});
}
The adjacent function is working perfectly so I assume there is no JavaScript error.
Also, when I put in another function (for instance the adjacent function name in onchange), it is also working. The problem may be with this particular function name show_3ph3meter1().
Hi if you have some other java script written over there contains errors , this code wont work.
So better have like this
<select class="style" onchange="//do something like this
//var e = document.getElementById('selectelement'); //if (e) e.value=100;" />
please check in IE browsers to get the java script errors. write entire code in that change event
First check your calling function name
if this is correct then just write
onchange="javascript : show_3ph3meter1(this)"
and get value on the function
3 else try the access value in function with selector
var elem = document.getElementById("short_code"),
selectedNode = elem.options[elem.selectedIndex];
var valu = selectedNode.value;
I am having some problems with Javascript :(
This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.
Here is the Script (in head tag):
<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>
Here is the HTML code:
<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>
I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?
There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code
resetDefault();
{if (this.value.length==0);
this.value="default";}
so that it has valid syntax, like this:
function resetDefault(){
if(this.value.length == 0){
this.value = "default";
}
}
The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change.
Change the onblur javascript so that it passes in a parameter to the function:
onblur="resetDefault(this);"
and change the function so it accepts a parameter:
function resetDefault(that){
if (that.value.length == 0){
that.value="default";
}
}
The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:
that.value = that.getAttribute("default");
Try it out on JSFiddle
The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.
<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>
You need to define the resetDefault() function like so:
function resetDefault() {
// Function stuff here
}
I have a classic table / thead / tbody structure, which I add a line at the end of the tbody. The line contains only an input element. The code works in Firefox 3.6 but not in Chrome v5 or IE8. I'm using jQuery 1.4.2.
Does not work:
$("#" + AJAX_ID).parent().find('tr:last > td:nth-child(2) > input').focus();
Does work:
$("#" + AJAX_ID).parent().find('tr:last > td:nth-child(2) > input').css('background-color', 'red');
even setting an ID on the input, and using document.getElementBuId('id').focus() doesn't work.
*** edit ***
The site is pretty complex (mix of template / static html and dynamic html), but the table
looks like this (rendered html in chrome, layout via tidy) : http://pastebin.com/PHqxAEVm
*** edit 2 ***
Even $("#lectures").find("input:last").focus(); called from the ajax callback doesn't do anything.. $("#lectures").find("input:last").css('background-color', 'red'); turns one red though, but the focus goes to the address bar.
Here's a dump of the returned object from the selector:
http://pastebin.com/Jdw1TZXf
*** edit 3 ***
Here's the JavaScript code that builds the table: http://pastebin.com/cbCfi0UY
on page load, oContainer is $("#lectures") while after the ajax call it's $("#" + AJAX_ID).parent(), which is supposed to point to the table's tbody
*** edit 4 ***
Hard problem... here's the full lectures.js file: http://pastebin.com/Jkg0DZqa
batisses and compteurs are json objects loaded via the template. the user select a batisse then a compteur then press a button that calls buildAjout(), which calls in this example buildElectric($("#lectures"), compteur);. Once the line is filled bu the user, onBlurLecture(tr_parent) is called, the data is sent to the server via AJAX and function callback_compteurs_lecture_add(AJAX_ID) is called after the ajax call is complete. The function SendCommand is a custom function which use jQuery ajax.
The creation of the first input line (and the focus) works, but not the one created in the callback of the ajax.
*** edit 5 ***
The full rendered page looks like: http://pastebin.com/UfBYcjX3
I shortened the batisses variable. The (full) page has no JavaScript errors.
In Chrome's JavaScript console, I cannot focus the inputs.
*** edit 6 ***
Wrong function name in this question for SendCommand. fixed.
Solution found:
.focus() doesn't work on an input while orher attributes works
What ID are you targeting? Because if I replace $("#" + AJAX_ID) with $('table') it works -> demo (at least in Chrome)
and if I wrap the function inside a $(document).ready(function(){...}) it works in IE -> demo
I'm still looking to see what the problem might be, but I have a few comments about your code so far.
I haven't tested this, but I creating a jQuery object then appending another object inside ends up taking a lot of time because of the number of function calls. I've found it easier to just build up a string and only use one append. This example makes it easy to read:
var table = '\
<table style="width: 100%">\
<thead>\
<tr>\
<th>Numéro</th>\
<th>litre</th>\
<th style='width: 100px;'>Status</th>\
</tr>';
// append more to the string
table += '<tbody>.....</tbody></table>';
$('body').append(table);
I found this bit of code and I just wanted to show you that you can shorten it:
$("#no_batisse").css('display', 'none');
$("#lectures").html("");
$("#lectures").css('display', '');
shortens to:
$("#no_batisse").hide();
$("#lectures").empty().hide();
Instead of calling this function after each row addition, you could try adding a live function once that works with dynamically added content:
$(oLigne).find("input").blur(function() { onBlurLecture(oLigne); });
try running this when you initialize the script (just once)
$('#lecture').find('input').live('blur', function(){
onBlurLecture( $(this).closest('tr') );
})
I'll keep looking!
EDIT:
If your code is being triggered via some element that has a default behavior (like an <a> element), try adding return false; to the end of its callback.
Alternatively, if you give a parameter to the event handler's function, like function(e) {...}, you can call e.preventDefault() from within the callback instead of return false;.
First, I don't know if this is the issue, but IDs can not start with a number.
Second, which element has the AJAX ID that are you using? You'll get different results depending on that.
To avoid any ID issues, you could do:
$("#lectures").find('tr:last > td:nth-child(2) > input').focus();
or if you want it to be relative, do:
$("#" + AJAX_ID).closest('tbody').find('tr:last > td:nth-child(2) > input').focus();
got it!
I use "tab" (tabulation) to switch to the next input while writing in them. At the last one, the focus goes out of the window so I cannot set it. I converted the last column "status" into a input so it gets the focus while onBlur is executed. When the ajax load callback is called, the new line is added and the input is focused as it should.
Chrome: works
Firefox: works
IE8: works (with fix)
spent 1½ day on that lol
thanks everyone!
Try to trigger .focusin() (this was added in jQuery's 1.4) See documentation.