Javascript Append and Add Selected - javascript

I'm trying to add selected to the option value which is rendered already within the object, but the below is not adding selected to the option value even they are equal. Ignoring the adding selected, is it because after doing this with appending?
eventClick: function(calEvent, jsEvent, view) {
var startFormat = $.fullCalendar.formatDate(calEvent.start, "dd / MM / yyyy");
var form = $("<form id='changeName'>" +
"<h3 class='eventHeader'>Edit Event: " +startFormat+ " </h3>" +
"</div></form>");
form.append("<div class='controls'>" +
"<label class='control-label' for='title'>Language: </label>" +
"<select class='span3' id='lang' name='lang'>" +
<?php foreach($languages as $language): ?>
"<option value='<?=$language->id;?>'><?=$language->title;?></option>" +
<?php endforeach; ?>
"</select>" +
"</div>");
$("#lang option").each(function(){
if ($(this).val() == calEvent.lang)
$(this).attr("selected","selected");
});
}

instead of this:
$(this).attr("selected","selected");
try using .prop():
$(this).prop("selected", true);
Updates:
you can use .done() method and use change event instead:
form.append("<div class='controls'>" +
"<label class='control-label' for='title'>Language: </label>" +
"<select class='span3' id='lang' name='lang'>" +
<?php foreach($languages as $language): ?>
"<option value='<?=$language->id;?>'><?=$language->title;?></option>" +
<?php endforeach; ?>
"</select>" +
"</div>").done(function(){
$(document).on('change', "#lang", function(){
$('option', this).each(function(){
if ($(this).val() == calEvent.lang)
$(this).prop("selected", true);
});
}).change(); //<------fire the change event here when appended in dom
});

this is just an example:
<?php
$array = array('lang1' => 'option1', 'lang2' => 'option2');
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<select id="a_select"></select>
<script>
$(function() {
var select_keys = [<?php foreach ($array as $key => $value) {echo "'$key', ";} ?>];
var select_values = [<?php foreach ($array as $value) {echo "'$value', ";} ?>];
$(select_values).each(function(i, item) {
var option = $('<option>'+ item +'</option>');
option.attr('value', select_keys[i]);
$('#a_select').append(option);
});
});
</script>
</body>
</html>
update: key values is added.
you may load this values from another script with ajax, that's gonna be easier & cleaner.

Related

PHP: Two <select>, first one allready fill, the second one I want to fill with values

I am have this issue:
<fieldset>
<?php
echo form_open('rssFeedReader/addSource');
echo '<h2><small>(*) Select in which category you want to add a new Rss Source </small><h2>';
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="category" id="category">';
foreach( $categories as $row )
{
// here i have some values from my database
echo '<option value="'.$row->id.'">' . $row->category_name . '</option>';
}
echo '</select>';
echo '</div>';
// NOW, HERE I WANT TO PUT ANOTHER <SELECT>
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="anotherID" id="anotherID">';
foreach( $array as $r)
{
// here i have some values from my database
echo '<option value="'.$r->something.'">' . $r->something_else. '</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('class' => 'btn btn-primary btn-lg btn-block', 'id' => 'remove_source', 'name' => 'remove_source', 'value' => 'Remove Source'));
echo '</div>';
?>
<?php echo validation_errors('<p class="error">'); ?>
Now, what I want to do.
The second select list is empty initially.
I want to fill it with values depending of what is chose in first select list.
How can I do that? To fill the second select list only if something is selected in first select list.
MrCode has a nice example for you.
Using Ajax To Populate A Select Box
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#category').on('change', function (){
$.getJSON('select.php', function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
$('#anotherID').html(options);
});
});
});
</script>
Your select.php should json_encode() the data which you want to fill your select with
The best way to handle this would be to populate the list after you made a change on the first list. For example.
$("#category").on("change", function(){
var selectedValue = $(this).val();
$.get("some.php?value=" + selectedValue, function(response){
var options = "";
for(var i = 0; i < response.length;i++){
var val = response[i];
options += "<option value='" + response[i].id + "'>" + response[i].name + "</option>";
}
$("#anotherID").empty().append(options);
});
}
I had to make several assumptions. for example your some.php will take a value parameter. The return is json array [{id:1, name:"option 1"}, {id:2, name:"option 2"}]. Please keep this in mind.

How would i change a <div> border colour when a drop down box is selected

Hi I am trying to get a HTML <div> to change its border colour when I select one of the drop down boxes in side it.
I have tried something simple like:
<style>
#select_Academic:hover{border:1px solid red;}
#select_Academic:focus{border:1px solid red;}
#select_Academic:active{border:1px solid red;}
</style>
The html is:
echo "<div id=\"Options\">";
include "select.class.php";
echo "<form id=\"select_Academic\">";
echo "<div class=\"Select_Option\">";
echo "Choose a subject:";
echo "</div>";
echo "<select style=\"width:200px; margin-left:10px;\" id=\"category\" name=\"cat\" >";
echo $opt->ShowCategory();
echo "</select>";
echo "<br />";
echo "<br />";
echo "<div class=\"Select_Option\">";
echo "Choose a section:";
echo "</div>";
echo "<select style=\"width:200px; margin-left:10px;\"id=\"type\">";
echo "<option value=\"%\">";
echo "Section";
echo "</option>";
echo "</select>";
echo "<br />";
echo "<br />";
echo "<div class=\"Select_Option\">";
echo "Choose a principle:";
echo "</div>";
echo "<select style=\"width:200px; margin-left:10px;\"id=\"principle\">";
echo "<option value=\"%\">";
echo "Principle";
echo "</option>";
echo "</select>";
echo "<br />";
echo "<br />";
echo "<input style=\"margin-left:10px;\" type=\"submit\" value=\"Search\"/>";
echo "</form>";
echo "</div>";
but when the mouse has left the div the border colour is no longer showing and I understand why just wondering whats the best possible way to do this.
I have JavaScript linked to these boxes I don't know if you could add something into this JavaScript to achieve the same results.
The JavaScript I have got :
$(document).ready(function()
{
$("select#type").attr("disabled","disabled");
$("select#category").change(function()
{
var id = $("select#category option:selected").attr('value');
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>");
$.post("select_type.php", {id:id}, function(data)
{
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("select#principle").attr("disabled","disabled");
$("select#type").change(function(){
var id = $("select#type option:selected").attr('value');
$("select#principle").attr("disabled","disabled");
$("select#principle").html("<option>wait...</option>");
$.post("select_principle.php", {id:id}, function(data){
$("select#principle").removeAttr("disabled");
$("select#principle").html(data);
});
});
$("select#career").attr("disabled","disabled");
$("select#jobrole").change(function(){
var id = $("select#jobrole option:selected").attr('value');
$("select#career").attr("disabled","disabled");
$("select#career").html("<option>wait...</option>");
$.post("select_career.php", {id:id}, function(data){
$("select#career").removeAttr("disabled");
$("select#career").html(data);
});
});
$("form#select_Academic").submit(function()
{
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
var princ = $("select#principle option:selected").attr('value');
$txt = cat + "#" + type + "#" + princ;
var id = $("select#type option:selected").attr('value');
$.post("get_results.php", {comboboxselections:$txt}, function(data){
$("#ResultList").html(''+data);
});
if(cat>0 && type>0 && princ>0)
{
}
else
{
$("#ResultList").html("you must choose three options!");
}
return false;
});
$("form#Select_Job").submit(function()
{
var job = $("select#jobrole option:selected").attr('value');
var car = $("select#career option:selected").attr('value');
$txt1 = job + "#" + car;
var id = $("select#career option:selected").attr('value');
$.post("get_jobresults.php", {comboboxselections1:$txt1}, function(data){
$("#ResultList").html(''+data);
});
if(job>0 && car>0)
{
}
else
{
$("#ResultList").html("you must choose two options!");
}
return false;
});
});
</script>
any help would be much appreciated I am open to all suggestions such as jquery
Html:
<div id="dv">
<select id="ddl">
<option>Select</option>
<option>One</option>
<option>Two</option>
</select>
</div>
Jquery:
$( "#ddl" ).change(function() {
alert($(this).val());
$('#dv').addClass('active');
});
Demo:
http://jsfiddle.net/K7YmM/
You need to handle the drop down's change event and in the event handler, apply your CSS class based on the selected value. Here is a JSFiddle with an example: http://jsfiddle.net/6AUg2/2/

Auto change option value in PHP/MYSQL

$MethodLocationFrom =mysql_query("
SELECT DISTINCT Location_From AS 'locationFrom'
FROM trip
");
echo "<form action='confirmation.php' method='post'>";
echo "<select class = 'LocationFrom' size='1' name='locationFrom' id='locationFrom'>";
while($check = mysql_fetch_array($MethodLocationFrom))
{
echo "<option value='" . $check['locationFrom'] . "'>" . $check['locationFrom'] . "</option>";
}
echo"</select>";
$MethodLocationTo =mysql_query("
SELECT DISTINCT Location_To AS 'locationTo'
FROM trip
");
echo "<select class = 'LocationTo' size='1' size='1' name='locationTo' id='locationTo'>";
while($check = mysql_fetch_array($MethodLocationTo))
{
echo "<option value='" . $check['locationTo'] . "'>" . $check['locationTo'] . "</option>";
}
echo"</select>";
Hi guys! I'm making a shuttle reservation system, I'm having trouble with the option boxes, what I want to do is when I select a place from Location from (first option box) that location would automatically be remove in the location where I want to go (second box) How can I do that?
Ok, let me have a go, with a personal twist
assume the result of iteration to be (reduced for brevity)
<select id="locationFrom">
...
<option value="$from">($from)</option>
</select>
<select id="locationTo">
...
<option value="$to">($to)</option>
</select>
I assume the values of each option-set are the same.
let's get dirty with javascript. Mind you, this is long and has no comments, review it, test it and give me feedback if you find an error.
// script.js
(function(){
var selectFrom, selectTo, unsetChild, nextSibling,
onSelect, removeOption, recoverOption,
loadWin, unloadWin;
onSelect = function () {
var idx = this.selectedIndex;
if (idx !== -1) {
if (unsetChild) {recoverOption();}
removeOption(this.options[idx].value);
}
};
removeOption = function (value) {
unsetChild = selectTo.querySelector('[value="'+value+'"]');
nextSibling = unsetChild.nextSibling;
selectTo.removeChild(unsetChild);
};
recoverOption = function () {
nextSibling
? selectTo.insertBefore(unsetChild,nextSibling)
: selectTo.appendChild(unsetChild);
nextSibling = unsetChild = null;
};
loadWin = function () {
selectFrom = document.getElementById('locationFrom');
selectTo = document.getElementById('locationTo');
selectFrom.addEventListener('change',onSelect,false);
};
unloadWin = function () {
selectFrom.removeEventListener('change',onSelect,false);
selectFrom = selectTo = nextSibling = unsetChild = null;
};
window.addEventListener('load',loadWin,false);
window.addEventListener('unload',unloadWin,false);
});
I've worked out a jQuery solution (tested in Google Chrome):
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
function jqyHideSelectedOption(objSelect) {
var strIDSeleted = objSelect.id;
var strID2Handle;
if(strIDSeleted == "locationFrom")
{
strID2Handle = "#locationTo";
}
else
{
strID2Handle = "#locationFrom";
}
strIDSeleted = "#" + strIDSeleted;
//
// show all options: ie, restore default settings.
//
jQuery(strIDSeleted + " option").show();
jQuery(strID2Handle + " option").show();
//
// hide some options in the corresponding select:
//
var selectedCity = jQuery(strIDSeleted).val();
if(jQuery(strID2Handle).val() == selectedCity) {
jQuery(strID2Handle).val(null);
}
jQuery(strID2Handle + " option[value='" + selectedCity + "']").each(function() {
jQuery(this).hide();
});
}
</script>
</head>
<body>
<?php
//
//...
//
$MethodLocationFrom = mysql_query("
SELECT DISTINCT Location_From AS 'locationFrom'
FROM trip
");
echo "<form action='confirmation.php' method='post'>";
echo "<select class = 'LocationFrom' size='1' name='locationFrom' id='locationFrom' onchange='jqyHideSelectedOption(this)'>";
while($check = mysql_fetch_array($MethodLocationFrom))
{
echo "<option value='" . $check['locationFrom'] . "'>" . $check['locationFrom'] . "</option>";
}
echo"</select>";
$MethodLocationTo = mysql_query("
SELECT DISTINCT Location_To AS 'locationTo'
FROM trip
");
echo "<select class = 'LocationTo' size='1' size='1' name='locationTo' id='locationTo' onchange='jqyHideSelectedOption(this)'>";
while($check = mysql_fetch_array($MethodLocationTo))
{
echo "<option value='" . $check['locationTo'] . "'>" . $check['locationTo'] . "</option>";
}
echo"</select>";
//
//...
//
?>
</body>
</html>
For the from city #locationFrom select, an onchange='jqyHideSelectedOption(this)' is used.
When a city is selected in this select, we hide this city name in the list of #locationTo select. If we choose another city, the hidden city is again shown in the destination list, so again available for destination selection.
If a destination is chosen, this city will be hidden in the from cities list.
We don't remove any option from the 2 select's, but rather temprarily hide it, as it's useful if another city is selected, and must be present for customer's selection.

Two Selectboxes - load by selection

I want, if I select a value in selectbox 1, that selectbox2 is loaded with values that are dependet on selectbox1.
Here´s how I tried:
<head>
<script src="jquery/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#selectbox1").change(function(){
var value = $(this).children('option.selected').val();
$("#selectbox2").load("php/loadteams.php", {value: value} );
});
});
</script>
</head>
<body>
<?php
include 'php/db.php';
$res = mysql_query("select * from liga", $connection);
echo '<select id="selectbox1">';
while($val = mysql_fetch_array($res)) {
echo '<option value="'.$val['id'] .'">' . $val['name'] . '</option>';
}
echo '</select>';
mysql_close($connection);
?>
<select id="selectbox2"> </select>
Like you see, I tried with jquery. The file loadteams.php looks like that:
<?php
include 'php/db.php';
$ligaid = mysql_real_escape_string($_POST['value']);
$result = mysql_query("select * from mannschaft where liga = '" . $ligaid . "'", $connection);
while($te = mysql_fetch_array($result)){
echo '<option> ' . $te . '</option>';
}
?>
I don´t know where my mistake is - can you help me?
You should try using the :selected selector, instead of .selected which would match a class with the name selected.
Also, I believe the .load() method posts data through HTTP GET, so I believe you would have to use $_GET["value"] instead of $_POST['value'].
Correction:
As you are providing the data as an object, it IS posted through HTTP POST, so strike my above statement. From the jQuery documentation:
The POST method is used if data is provided as an object; otherwise, GET is assumed.

Hide table row with value of option box in wordpress with jquery

I have a table with an input field in a table row and an option boxe and I want, that the <tr> with the input field only appears when a specific value in the option box are selected. So far I have the following coding, it hides my <tr> with the input field, but never displays it again.
$script = <<< EOF
<script type='text/javascript'>
jQuery(document).ready(function($) {
$('#row_sports').hide(); //works
if($('#sel_rugby').is(':selected') || $('#sel_climbing').is(':selected')){
$('#row_sports').show();
}else{
$('#row_sports').hide();
}
});
</script>
EOF;
echo $script;
echo '<table border="1">';
echo ' <tr>';
echo ' <td>';
echo ' <select name="sports">';
echo ' <option>Baseball</option>';
echo ' <option id="sel_rugby">Rugby</option>';
echo ' <option>Soccer</option>';
echo ' <option>Sailing</option>';
echo ' <option id="sel_climbing">Climbing</option>';
echo ' </select>';
echo ' </td>';
echo ' </tr>';
echo ' <tr id="row_sports">';
echo ' <td>';
echo ' <input name="sports_cl_rg" />';
echo ' </td>';
echo ' </tr>';
echo '</table>';
BR & thx,
mybecks
<script type='text/javascript'>
jQuery(document).ready(function($) {
$('#row_sports').hide(); //works
$('select').change(function() {
if($('#sel_rugby').is(':selected') || $('#sel_climbing').is(':selected')){
$('#row_sports').show();
}else{
$('#row_sports').hide();
}
});
});
</script>
use change function too.. here it works
Try this code:
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function($) {
$('#row_sports').hide(); //works
$('select[name="sports"]').change(function() {
var trig = ["Rugby", "Climbing"]; // set elements here
if (trig.indexOf($(this).val()) > -1) {
$('#row_sports').show();
} else {
$('#row_sports').hide();
}
});
});
</script>
It would be better if you put id in all options or compare them by the text instead of id it will be event better. I mean use Climbing instead of sel_climbing. Also give id to select to access it as you may have many selects on the page. I changed it to work as you code but you can follow my recommendation if you like. Demo available here JsFiddle
$('select').change(function() {
alert($('#sports option:selected').text());
$('#row_sports').hide(); //works
if($('#sports option:selected').attr('id') == "sel_rugby" || $('#sports option:selected').attr('id') == "sel_climbing"){
$('#row_sports').show();
}else{
$('#row_sports').hide();
}
});​

Categories