the project is an MVC project writen in PHP
I have an AJAX call in a veiw that echoes, into a div, a bit of Javascript that does some things on the page. At the end of the script is a piece of JQuery that should change a select boxes selected option. I did plenty of research into switching select options on this website and others, and after some playing around i got this bit of code to work:
function filterSet(optValue){
$("#mySelect option").prop('selected', false)
.filter('[value="'+ optValue +'"]')
.prop('selected', true);
}
The strange thing is, that sometimes it works, sometimes it doesnt. Testing it over the last hour or so, it hasent worked once, but it did work before that, and the only change to the code that i made is a change of the enclosing method name.
the error the console is giving is 'ReferenceError: maple is not defined' where 'maple' is the word in the optValue variable.
ReferenceError: maple is not defined
i dont understand why i would get an undefined error considering the value of the select option is hardcoded into the select html, and ive tried the jquery with hardcoding the option value to what the variable is suppose to pass in, but i still get the same error, this is strange because there once was a time when this code worked perfectly! more than once actually, it worked when testing it several times! but know its not.
select box html:
<select id="mySelect">
<option value = 'all' selected> Ward </option>
<option value = 'maple'> Maple </option>
<option value = 'oak'> Oak </option>
<option value = 'w3'> Ward 3 </option>
<option value = 'w4'> Ward 4 </option>
<option value = 'w5'> Ward 5 </option>
<option value = 'w6'> Ward 6 </option>
</select>
can anyone shed some light on this?
how the filterSet method is called. An ajax call causes this script to be echoed into a div on the page, on the success callback of the ajax call filterSet() is called.
echo '
<script type="text/javascript">
function locateSpecific(){
scale = 1;
height =' . $height . '
width =' . $width . '
var imageUrl = "' . $imageURL . '";
var bounds = new L.LatLngBounds([0, 0], [height / scale,width / scale]);
map.removeLayer(markerGroup);
L.imageOverlay(imageUrl, bounds, { noWrap: true, maxZoom: 3, minZoom: -3 }).addTo(map);
}
filterSet('.$loc.');
</script>
';
Your problem lies in the PHP code. You aren't quoting the string that you are passing to the function, so it thinks that it's a reference.
Solution:
Here is the erroneous line:
filterSet('.$loc.');
You need to make sure to output quotes around it:
filterSet("'.$loc.'");
Explanation:
When $loc is set to the string "maple" it will output the following string to the web browser.
filterSet(maple);
The javascript interpreter will then try to find the variable maple instead of using the string "maple". It will then throw a reference error because it can't find it.
With the updated code the PHP will instead send the following.
filterSet("maple");
Since this is a string it will now work as expected.
Use a function as argument for the filter method :
function filterSet(optValue){
$("#mySelect option")
.filter(function () { return $(this).val() == optValue; })
.prop('selected',true)
}
filterSet('oak');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
<option value = 'all' selected> Ward </option>
<option value = 'maple'> Maple </option>
<option value = 'oak'> Oak </option>
<option value = 'w3'> Ward 3 </option>
<option value = 'w4'> Ward 4 </option>
<option value = 'w5'> Ward 5 </option>
<option value = 'w6'> Ward 6 </option>
</select>
Related
I have a dropdown mean with various values...
<select id="number1a" onChange="Addition()">
<option value="0" selected>-</option>
<option value="10">10</option>
<option value="7.5">7.5</option>
</select>
<select id="number1b" onChange="Addition()">
<option value="0" selected>-</option>
<option value="5">5</option>
<option value="5.5">5.5</option>
</select>
and a javascript function that adds the values and displays it it a div...
<script>
function Addition(){
number1a = parseInt(document.getElementById('number1a').value);
number1b = parseInt(document.getElementById('number1b').value);
output = number1a + number1b;
document.getElementById('score').innerHTML = +output;
</script>
and the div to display the maths...
<div id="score"></div>
The function works and display a number but it ignores the decimal, so if I select from the dropdown '10' and then '5' from the next dropdown, it display 15 in the , but if i select 10 and 5.5 it display 16 and not 15.5?
I have tried to add in .toFixed(2); but it has no effect, I get the same result. for example...
var output = outputnum.toFixed(5);
document.getElementById('score').innerHTML = +outputnum;
Any help would be much appreciated.
The Problem is in these lines:
number1a = parseInt(document.getElementById('number1a').value);
number1b = parseInt(document.getElementById('number1b').value);
The function parseInt always returns an Integer value (as described here). So instead of 5.5, it will return the nearest Integer, which is 6.
To get the actual value of 5.5, you will need to use the parseFloat() method, as described here. So just change these two lines to:
number1a = parseFloat(document.getElementById('number1a').value);
number1b = parseFloat(document.getElementById('number1b').value);
and it should work.
So to continue my last question (link). I've finally got that sorted out (with help), but now the value of the name is only the first value of the drop down list.
A brief explanation, I have 2 drop down menu's and when you select a option from one (A) the other drop down menu is updated (B). I know it has something to do with an array but I can't figure this out.
Here are my files.
HTML
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<?php
$sttub = str_replace('&', 'en', $stub);
$q = $row["Categorie"];
echo "
<option class='dropdownmenu_A' value='".$sttub."' name='".$q."'>"
.$row["Categorie"]."
<span style='font-size:1.2rem;color:#F8F8F8;'>
(" . $row['x'] . ")
</span>
</option>
";
}}?>
</select>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
JavaScript
$(function(){
$('#main_cat').change(function(){
var $mainCat=$('#main_cat').val();
var $mainName = $(".dropdownmenu_A").attr("name");
// call ajax
$("#sub_cat").empty();
$.ajax({
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_call&main_catid=' + $mainCat + '&main_name=' + $mainName,
success:function(results)
{
// alert(results);
console.log($mainCat,$mainName);
$("#sub_cat").removeAttr("disabled");
$("#sub_cat").append(results);
}
});
}
);
});
function.php
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$q = $_POST['main_catid'];
$x = $_POST['main_name'];
echo '<option value="-1" selected="selected">'.$x.'</option>'.$option;
die();
} // end if
}
I have tried using <select id="main_cat" name="main_cat[]"> like I found on google but this didn't work. Using $x[] = $_POST['main_name']; just echos the word Array. How do I get this to work and display the correct option that is selected and not just the first every time.
To be clear, here are my drop down menu's (sometimes my brain goes faster then I can type, so I hope it's clear).
select{height:30px}
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_A' value='option-1' name='Option 1'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
</select>
<select id="sub_cat" name="sub_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_B' value='sub-option-1' name='Sub Option 1'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
</select>
So right now if I select Option 1 from dropdownmenu_A it only echo's the first value from dropdownmenu_A to dropdownmenu_B and not Option 2 or Option 3.
1- You can't have <span/> tags inside <option/> tags as the latter cannot have any child elements.
2- <option/> doesn't have a name attribute. If you want to create a custom attribute, use HTML5 data attributes. That's what they are for.
3- printf is your new friend.
printf('<option class="dropdownmenu_A" value="%s" data-name="%s">%s (%s)</option>', $sttub, $q, $row["Categorie"], $row['x']);
4- I believe the problem is $(".dropdownmenu_A").attr("name") as this would always pull the same name and not the selected name. In your particular case, I would do
$(function(){
$('#main_cat').change(function(){
var $option = $(this).find('option:selected'),
id = $option.val(),
name = $option.data('name');
// open your browser's console log and ensure that you get the correct values
console.log(id, name);
$("#sub_cat").empty();
// call ajax
$.ajax({
url: "<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data: {
action: 'my_special_ajax_call',
main_catid: id,
main_name: name
},
success: function (results) {
$("#sub_cat").removeAttr('disabled').html(results);
}
});
});
});
You should add a selected attribute to your selected option:
https://www.w3schools.com/tags/att_option_selected.asp
I have a select box which more or less looks like this :
<select id="select_experience">
<option value="1,2">1-2</option>
<option value="3,4">3-4</option>
<option value="5,6,7,8,9">5-9</option>
<option value="10,11,12,13,14,15">10-15</option>
<option value="15+">15+</option>
</select>
This is a search filter, so that if I select an option out of this, it will create a condition for querying. I have a column in mysql which shows tutor experiences :
tutorid | experience
1 | 5
2 | 1
3 | 10
4 | 3
My current query looks like this:
$query_tutors = $this->db->get_where("tutor_info", array("tutor_id" => $id, "I need to add that selectbox selected option here."));
My question is :
Where will I do the explode thing? and how will I check for 15+ in that query?
Lets assume you stored select_experience input to $id variable.
You can use following code
$this->db->from('tutor_info');
if (strpos($id,'+') !== false)//if 15+
{
$ranges=explode('+',$id);//get the integer value.You may need to check more to make sure it is intger
$this->db->where('tutorid >=',$ranges[0]);//only >=15
}
else if (strpos($id,'-') !== false)//if range like 5-9
{
$ranges=explode('-',$id);
$this->db->where('tutorid >=',$ranges[0]);//>=5
$this->db->where('tutorid <=',$ranges[1]);//<=9
}
$query_tutors=$this->db->get();
Note
This answer is for your first revision where values was like 1-2,3-4,5-9..
in your model, get the selected option
$experience_level = $this->input->post("select_experience");
This will work only if change the html like this
<select name="select_experience" id="select_experience">
<option value="1,2">1-2</option>
<option value="3,4">3-4</option>
<option value="5,6,7,8,9">5-9</option>
<option value="10,11,12,13,14,15">10-15</option>
<option value="15+">15+</option>
</select>
If not you can either submit the value by Ajax...
Any way get the selected option value to $experience_level
Then do condition check like this
if($experience_level !='15+'){
$this->db->where_in("experience", explode(",", $experience_level);
}else{
$this->db->where("experience >", 15);
}
<select onchange="showResult(this.value)">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>
In above code, the value of each <option> has been passed as parameter in showResult().
My questions is how to pass the content of option element (i.e.'London','France', 'Berlin', 'Rome') as parameter in showResult().
Many Thanks
[yourselect].options[0].text returns 'London', [yourselect].options[1].text France, etc. So, in other words, for every option of an options-nodeList the property text contains its content.
write this code
<select onchange="showResult(this.options[this.selectedIndex])">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>
so you will pass the whole selected option node to the showResult function and you will be able to access both the value and text
function showResult(opt) {
alert(opt.value); /* e.g. DDD */
alert(opt.text); /* e.g. Rome */
}
Example Fiddle : http://jsfiddle.net/xypGa/
Try this.options[this.selectedIndex].text, been a while since I did this without jQuery.
function showResult()
{
var value = this.options[this.selectedIndex].value;
var content = this.options[this.selectedIndex].text;
}
Is this question about your issue - Get selected value in dropdown list using JavaScript? ?
in general - document.FORM.FIELDMANE.options[document.FORM.FIELDMANE.selectedIndex].value
in your case it should be i suppose - onchange="showResult(this.options[this.selectedIndex].value)
Instead of passing this.value (the value property of the select element), pass this (the select element), i.e. onchange="showResult(this)", and use code like
function showResult(selectElem) {
var optionText = selectElem.options[selectElem.selectedIndex].text;
alert(optionText); // replace by real code that uses the string
}
An added advantage is that now the function has access to the entire element, so that if you later need to use the value property, too, in the function, you can do that without modifying the function calls.
<select onchange="showResult(this.options[this.selectedIndex].text)">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>
I need help solving a simple requirement.
<select id="my-select1">
<option value="1">This is option 1 ({myop1}|OP)</option>
<option value="2" selected>This is option 2 ({myop1}|OQ)</option>
<option value="3">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="1">This is option 1 ({myop2}|PP)</option>
<option value="2">This is option 2 ({myop2}|PQ)</option>
<option value="3" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="1">This is option 1 ({myop3}|QP)</option>
<option value="2">This is option 2 ({myop3}|QQ)</option>
<option value="3" selected>This is option 3 ({myop3}|QR)</option>
</select>
See the HTML above, I want to recreate my array:
combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
INTO
combo = ["abc-OQ-PR", "def-PR"];
based on the selected options.
Another thing to note is that I cannot simply change the value of the options of the select box, meaning to say the HTML is somewhat as it is, if it would help, the only part i can restructure on that HTML is the text content between <option></option>
I'm not sure, but I'm already spending a couple of hrs just to solve this problem. Maybe due to my limited jQuery knowledge.
Please help. thanks
Get the selected values into an associative array:
var pattern = {};
var s = $('select option:selected').each(function(){
var m = /\((.*?)\|(.*)\)/.exec($(this).text());
pattern[m[1]] = m[2];
});
Then you can replace each place holder in each string in the array with the corresponding value:
combo = $.map(combo, function(e){
return e.replace(/\{.*?\}/g, function(m){
return pattern[m];
});
});
Demo: jsfiddle.net/C97ma/
Based on the information you provided I'm don't get it 100% I guess. But whatever you're trying to do, I guess jQuerys .map() and $.map() would help you here.
Like
var arr = $('select').find('option:selected').map(function(index, elem) {
return elem.textContent || elem.text;
}).get();
Demo: http://www.jsfiddle.net/4yUqL/78/
Within the callback you can modify/match the text in any way you want/need. In your case I could imagine you want to use a regular expression to match the selected strings and recreate those somehow.
I figure you're using javascript for combining those (it can be done with PHP also)..
You need references to your selects, e.g. :
<script type="text/javascript">
a=document.getElementById("myselect").options[1];
</script>
This will assign the 2nd option value from the 'myselect' select element to the variable 'a'
To begin with I would change the values in the select box like this:
<select id="my-select1">
<option value="OP">This is option 1 ({myop1}|OP)</option>
<option value="OQ" selected>This is option 2 ({myop1}|OQ)</option>
<option value="OR">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="PP">This is option 1 ({myop2}|PP)</option>
<option value="PQ">This is option 2 ({myop2}|PQ)</option>
<option value="PR" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="QP">This is option 1 ({myop3}|QP)</option>
<option value="QQ">This is option 2 ({myop3}|QQ)</option>
<option value="QR" selected>This is option 3 ({myop3}|QR)</option>
</select>
Now to update your array:
var comboDef = ["abc-{myop1}-{myop2}", "def-{myop2}"];
var combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
function updateArray() {
combo = comboDef;
for (i in combo)
{
combo[i] = combo[i].replace("{myop1}",document.getElementById("my-select1").value);
combo[i] = combo[i].replace("{myop2}",document.getElementById("my-select2").value);
combo[i] = combo[i].replace("{myop3}",document.getElementById("my-select3").value);
}
}
Of course, this could be done better with proper arrays (if you gave your select boxes the same name you could iterate through them using document.getElementsByName()). The basic idea is the replace though which I trust is what you're looking for.