Onchange select without refresh - javascript

When change value my page is refresh because i have to send value to query data
but my selector doesn't show value when selected
<form name='active' action='' method='GET'>
<select class="form-control" id="section" name="section" onchange="list()" >
<option value="0"> - - Select All - - </option>
<?php
$section = $db->fetch();
foreach ($section as $key => $v) {
$section_name = $v['section'];
echo "<option value='".$section_name."'>",$section_name,"</option>";
}
?>
<script type="text/javascript">
function list(){
document.active.submit();
}
</script>

For an option in a dropdown other than the first one to be selected on page load, you have to add the selected="selected" attribute to one of the <option> elements like so :
<select class="form-control" id="section" name="section" onchange="list()" >
<option value="0"> - - Select All - - </option>
<option value="1" selected="selected"> I'm selected </option>
<option value="2"> I'm not selected </option>
</select>
In your case, it implies checking either the GET variable or the database value in your foreach loop to set the attribute accordingly.

Related

Having 2 different values in one <option> dropdown [duplicate]

I got a select tag with some options in a HTML form:
(the data will be collected and processed using PHP)
Testing:
<select name="Testing">
<option value="1"> One
<option value="2"> Two
<option value="3"> Three
</select>
Is it possible for an option to carry multiple values like when a user selects
"One", then a few other values related to this option will be written to the Database.
How should I design the select Tag so that each of the options can carry one than one value like this:
<select name="Testing">
<option value="1" value="2010"> One
<option value="2" value="2122"> Two
<option value="3" value="0"> Three
</select>
One way to do this, first one an array, 2nd an object:
<select name="">
<option value='{"num_sequence":[0,1,2,3]}'>Option one</option>
<option value='{"foo":"bar","one":"two"}'>Option two</option>
</select>
I achieved it by using the PHP explode function, like this:
HTML Form (in a file I named 'doublevalue.php':
<form name="car_form" method="post" action="doublevalue_action.php">
<select name="car" id="car">
<option value="">Select Car</option>
<option value="BMW|Red">Red BMW</option>
<option value="Mercedes|Black">Black Mercedes</option>
</select>
<input type="submit" name="submit" id="submit" value="submit">
</form>
PHP action (in a file I named doublevalue_action.php)
<?php
$result = $_POST['car'];
$result_explode = explode('|', $result);
echo "Model: ". $result_explode[0]."<br />";
echo "Colour: ". $result_explode[1]."<br />";
?>
As you can see in the first piece of code, we're creating a standard HTML select box, with 2 options. Each option has 1 value, which has a separator (in this instance, '|') to split the values (in this case, model, and colour).
On the action page, I'm exploding the results into an array, then calling each one. As you can see, I've separated, and labelled them so you can see the effect this is causing.
its possible to have multiple values in a select option as shown below.
<select id="ddlEmployee" class="form-control">
<option value="">-- Select --</option>
<option value="1" data-city="Washington" data-doj="20-06-2011">John</option>
<option value="2" data-city="California" data-doj="10-05-2015">Clif</option>
<option value="3" data-city="Delhi" data-doj="01-01-2008">Alexander</option>
</select>
you can get selected value on change event using jquery as shown below.
$("#ddlEmployee").change(function () {
alert($(this).find(':selected').data('city'));
});
You can find more details in this LINK
one option is to put multi value with comma seperated
like
value ="123,1234"
and in the server side separate them
When I need to do this, I make the other values data-values and then use js to assign them to a hidden input
<select id=select>
<option value=1 data-othervalue=2 data-someothervalue=3>
//...
</select>
<input type=hidden name=otherValue id=otherValue />
<input type=hidden name=someOtherValue id=someOtherValue />
<script>
$('#select').change(function () {
var otherValue=$(this).find('option:selected').attr('data-othervalue');
var someOtherValue=$(this).find('option:selected').attr('data-someothervalue');
$('#otherValue').val(otherValue);
$('#someOtherValue').val(someOtherValue);
});
</script>
What about html data attributes?
That's the easiest way.
Reference from w3school
In your case
$('select').on('change', function() {
alert('value a is:' + $("select option:selected").data('valuea') +
'\nvalue b is:' + $("select option:selected").data('valueb')
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<select name="Testing">
<option value="1" data-valuea="2010" data-valueb="2011"> One
<option value="2" data-valuea="2122" data-valueb="2123"> Two
<option value="3" data-valuea="0" data-valueb="1"> Three
</select>
In HTML:
<SELECT NAME="Testing" id="Testing">
<OPTION VALUE="1,2010"> One
<OPTION VALUE="2,2122"> Two
<OPTION VALUE="3,0"> Three
</SELECT>
For JS:
var valueOne= $('#Testing').val().split(',')[0];
var valueTwo =$('#Testing').val().split(',')[1];
console.log(valueOne); //output 1
console.log(valueTwo); //output 2010
For PHP:
$selectedValue= explode(',', $value);
$valueOne= $exploded_value[0]; //output 1
$valueTwo= $exploded_value[1]; //output 2010
I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.
HTML
<select class="example">
<option value="1" data-value="A">One</option>
<option value="2" data-value="B">Two</option>
<option value="3" data-value="C">Three</option>
<option value="4" data-value="D">Four</option>
</select>
JS
$('select.example').change(function() {
var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');
console.log(other_val);
});
If you're goal is to write this information to the database, then why do you need to have a primary value and 'related' values in the value attribute? Why not just send the primary value to the database and let the relational nature of the database take care of the rest.
If you need to have multiple values in your OPTIONs, try a delimiter that isn't very common:
<OPTION VALUE="1|2010">One</OPTION>
or add an object literal (JSON format):
<OPTION VALUE="{'primary':'1','secondary':'2010'}">One</OPTION>
It really depends on what you're trying to do.
Put values for each option like
<SELECT NAME="val">
<OPTION value="1:2:3:4"> 1-4
<OPTION value="5:6:7:8"> 5-8
<OPTION value="9:10:11:12"> 9-12
</SELECT>
At server side in case of PHP, use functions like explode
[array] = explode([delimeter],[posted value]);
$values = explode(':',$_POST['val']
The above code returns an array that has only the numbers and the ':' get removed
Simplest way to do this:
<select name="demo_select">
<option value='{"key1":"111","key2":"222"}'>option1</option>
<option value='{"key1":"333","key2":"444"}'>option2</option>
</select>
on controller decode the request value as given below:
$values = json_decode($request->post('demo_select'));
$val1 = $values->key1;
$val2 = $values->key2;
echo "Value 1: ".$val1;
echo "Value 2: ".$val2;
output for the first option:
Value 1: 111
Value 2: 222
output for the second option:
Value 1: 333
Value 2: 444
Use a delimiter to separate the values.
<select name="myValues">
<option value="one|two">
</select>
<?php>
$value = filter_input(INPUT_POST, 'myValues');
$exploded_value = explode('|', $value);
$value_one = $exploded_value[0];
$value_two = $exploded_value[1];
?>
Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010". But you would have to parse the value on the server.
Instead of storing the options on the client-side, another way to do this is to store the options as sub-array elements of an associative/indexed array on the server-side. The values of the select tag would then just contain the keys used to dereference the sub-array.
Here is some example code. This is written in PHP since the OP mentioned PHP, but it can be adapted to whatever server-side language you are using:
<FORM action="" method="POST">
<SELECT NAME="Testing">
<OPTION VALUE="1"> One </OPTION>
<OPTION VALUE="2"> Two </OPTION>
<OPTION VALUE="3"> Three </OPTION>
</SELECT>
</FORM>
PHP:
<?php
$options = array(
1 => array('value1' => '1', 'value2' => '2010'),
2 => array('value1' => '2', 'value2' => '2122'),
3 => array('value1' => '3', 'value2' => '0'),
);
echo 'Selected option value 1: ' . $options[$_POST['Testing']]['value1'] . '<br>';
echo 'Selected option value 2: ' . $options[$_POST['Testing']]['value2'] . '<br>';
This may or may not be useful to others, but for my particular use case I just wanted additional parameters to be passed back from the form when the option was selected - these parameters had the same values for all options, so... my solution was to include hidden inputs in the form with the select, like:
<FORM action="" method="POST">
<INPUT TYPE="hidden" NAME="OTHERP1" VALUE="P1VALUE">
<INPUT TYPE="hidden" NAME="OTHERP2" VALUE="P2VALUE">
<SELECT NAME="Testing">
<OPTION VALUE="1"> One </OPTION>
<OPTION VALUE="2"> Two </OPTION>
<OPTION VALUE="3"> Three </OPTION>
</SELECT>
</FORM>
Maybe obvious... more obvious after you see it.
<select name="student" id="student">
<option value="">Select Student</option>
<option value="Student Name|Roll No">Student Name</option>
</select>
<input type="submit" name="submit" id="submit" value="submit"></form>
i use data-attribute to get the value with simple javascript and blade template.
<select class="form-control" id="channelTitle" name="channelTitle" onchange="idChannels()">
#foreach($post['channels'] as $channels)
<option value="{{ $channels->channel_title }}" data-id="{{ $channels->channel_id }}">{{ $channels->channel_title }}</option>
#endforeach
</select>
the data-id result here
<div class="form-group">
<strong>Channel Id:</strong>
<input type="text" name="channelId" id="channelId" class="form-control" placeholder="Channel Id">
</div>
javascript
<script>
function idChannels(){
var elem=document.getElementById("channelTitle");
var id = elem.options[elem.selectedIndex].getAttribute('data-id');
document.getElementById("channelId").value = id;
} </script>
you can use multiple attribute
<SELECT NAME="Testing" multiple>
<OPTION VALUE="1"> One
<OPTION VALUE="2"> Two
<OPTION VALUE="3"> Three

Display option data with php and hide the similiar

I'm using php to select data from my database. I'm displaying it in a HTML select option tag. I have 100+ options and I want to hide which is the same as my selected data. For example:
<select class="form-control" id="type" name="type" required>
<option selected value='<?php echo $type; ?>'><?php echo $type; ?></option> // for example $type == "c"
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
For example the $type variable is "c". So it displays the option "c" twice. How can I easily hide always the one that I need if I have 100+ option values?
Manually remove all duplicate option tags with JavaScript and jQuery
let values = []
$("option").each((index, item) => {
let { value } = item //item.value is the value of our current option in the loop
// check if value is already in values array
if(values.includes(value)) {
// delete duplicate from the DOM
item.remove()
} else {
// push value to values array so that duplicates can be detected later on
values.push(value)
}
})
console.log(values)
<select class="form-control" id="type" name="type" required>
<option selected value="c">c</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Alternative solution
If your given options a, b, c, d are always the same you could setup a „blacklist“ in your PHP code and only echo out the html option element if it‘s not in this blacklist. Is this a possible solution for you?

how to check a value from select, if you choose to give a value then it is not necessary?

this is my html,
I have two select if one select contains a value, then the required attribute is deleted,and the third select must be required
<select class="form-control costume-{{$stud}}" name="subject-{{$stud}}[]" id="sub1" disabled="disabled">
<option value="" selected> --------Select-------- </option>
<option value="math,indonesia">Math (Indonesia)</option>
<option value="math,english">Math (English)</option>
</select>
<select class="form-control costume-{{$stud}}" name="subject-{{$stud}}[]" id="sub2" disabled="disabled">
<option value="" selected> --------Select-------- </option>
<option value="science,indonesia">Science (Indonesia)</option>
<option value="science,english">Science (English)</option>
</select>
<select class="form-control select-long costume-{{$stud}}" name="location_id[{{$stud}}]" disabled="disabled">
<option value="" selected> -----Select------</option>
#foreach ($venue as $row)
<option value="{{$row['location_id']}}">{{$row['location_name']}}</option>
#endforeach
</select>
<input type="checkbox" id="enableSelect-{{$stud}}" onclick="getCheck({{$stud}});">
and this is my jquery
function getCheck(id){
var e = document.getElementById("sub1");
var sub1 = e.options[e.selectedIndex].value;
console.log(sub1);
if($('#enableSelect-' +id).is(':checked')) {
$('.costume-' +id).prop("disabled", false);
$('.costume-' +id).prop("required", true);
$('.visibility').show();
}else{
$('.costume-' +id).prop("disabled", true);
$('.costume-' +id).prop("required", false);
$('.visibility').hide();
}
}
Your JS doesn't correspond to the HTML, the selectors don't match up.
I would check form values and set the required like this :-
$('select').on('change', function() {
if($(this).val() != ""){
$('select').prop('required',false);
}
});
This would work with your HTML as by default the select value is ""
You would also need required="true" on the and your default option should be something like this -
<option value="" disabled selected>Select your option</option>
on the select elements by default.

how to get selected item from combo box using javascript

Need to retrieve selected item from the select element using javascript.
<select id="selected">
<option value="Default Request" selected disabled>Default Request Service</option>
<option value="1">Anti-Virus Support and Services</option>
<option value="2">CSB - Request and Report Forms</option>
<option value="3">Email Support and Services</option>
<option value="4">Hardware Support and Services</option>
</select>
<input id="selected_display" type="text" value="" name="subject">
solution for you is in next code. You got 2 functions. First is for get value or text of selected item. second is used for set value to input
you have to add listener on on select tag and wait for change of the selected option
Enjoy!
function getOption(selector) {
return {
val: $(selector + ' option:selected').attr('value'),
text: $(selector + ' option:selected').text()
}
};
function setItem(toSelector, value) {
jQuery(toSelector).val(value);
}
var output;
jQuery('#selected').on('change', function(){
output = getOption('#selected');
setItem('#selected_display', output.val); //change to output.text to show text of selected output
});
https://jsfiddle.net/v4fwxeeu/3/
Maybe you want to try it with PHP:
<form Name="xxxx" class="xxxx" method="post" Action="xxxx">
<select id="selected" Name="selected>
<option value="Default Request" selected disabled>Default Request Service</option>
<option value="1">Anti-Virus Support and Services</option>
<option value="2">CSB - Request and Report Forms</option>
<option value="3">Email Support and Services</option>
<option value="4">Hardware Support and Services</option>
</select>
</form>
With PHP you can get the value of "selected" with:
<?php
$selected = $_POST['selected'];
echo $selected;
?>

Show default value of select item from dropdown in input

I have a dropdown looks like following:
<div class="col-md-2 padding-Zero" >
<select id="ddlCompare1" class="dropdown" onChange="javascript:CompareLoantype(true);" >
<option value="jumbo">Conv</option>
<option selected value="fha">FHA</option>
<option value="va">VA</option>
<option value="usda">USDA</option>
</select>
</div>
I want the selected default value to be asigned to the following input :
<input name="Compare_interest_rate" id="Compare_interest_rate" class="txt" type="text" size="6" maxlength="6" style="width:75%" />%</p>
I have the default values of the options on php, how can i point to them when i select items.
FHA value => <?php echo $interest_FHA_default; ?>
VA value => <?php echo $interest_VA_default;?>
USDA value => <?php echo $interest_USDA_default;?>
CONV value => <?php echo $interest_CONV_default;?>
How to show value in input depending on item selected in dropdown? if user select FHA item i need FHA default value in input?
I'm not sure that this what you want, when the user select from drop down the default value shown in the input (default value stored in data-default attribut).
NOTE : in my example i can't use php code that why i fix the values in data-default, you can replace the numbers by the php code for every item, e.g :
<option data-default='<?php echo $interest_FHA_default; ?>' value="fha">FHA</option>
Hope this helps.
$('#ddlCompare1').change(function(){
$('#Compare_interest_rate').val($(this).find(':selected').data('default'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-2 padding-Zero" >
<select id="ddlCompare1" class="dropdown">
<option data-default='1' value="jumbo">Conv</option>
<option data-default='2' value="fha" selected>FHA</option>
<option data-default='3' value="va">VA</option>
<option data-default='4' value="usda">USDA</option>
</select>
</div>
<input name="Compare_interest_rate" id="Compare_interest_rate" class="txt" type="text" size="6" maxlength="6" style="width:75%" />%</p>

Categories

Resources