I want to pass the value which I am taking from the javascript to a controller. But I don't use any function. I just want to access the value which I get from the view in the controller. I have the following view.
<select id="selected_year" name="selected_year" data-live-search="true" style="margin-left: 27px;" >
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
</select>
I am getting the value of the drop down using the following javascript.
<script type="text/javascript">
$("#selected_year").live('change', function() {
var selected_year = $(this).attr("value");
alert(selected_year);
window.location.reload();
});
</script>
I want to just pass the value I am getting from the above javascript into a controller. Is it possible to do it?
You would accomplish that either by sending a POST request that would be dispatched to a controller action (synchronously or asynchronously, depending on your need) or passing it as a query string in the url and then checking for it's presence in your controller.
You can send your data form view to controller via three way
1.POST ,GET(form submitio).
2.making it in link(URi segment)
3.via Ajax
You can use AJAX to submit everytime user change dropdown
var data = $('#selected_year').val();
$("selected_year").on('change',function(){
$.ajax({
url: yourcontroller,
type: 'POST',
data: data,
success: function (data) {
},
});
});
Create a controller to provide the dynamic part of the url.
<script type="text/javascript">
$("#selected_year").live('change', function() {
var selected_year = $(this).attr("value");
// NEXT 2 LINES ARE THE SOLUTION. substitute your own controller URL on the next line.
$url = '<?= base_url()index.php/controller/method?>/'+selected_year+'';
window.location.reload($url);
});
</script>
Here is your controller:
function method($year){
echo $year;
}
Related
I've created in an html webpage a dropdown with four options. It worked well but I realized that when the page was refreshed, the value would reset itself to the first option. Since I wanted the user's choice to be kept in memory, I added a javascript code snippet that I found somewhere.
It works very well, except that at the initialization the default value of the dropdown is an empty field.
I would need the first option to be displayed at initialization.
I guess it's easy but I don't know JavaScript at all. Could you please help?
Here is what the code looks like:
<select name="options" id='dropdown'>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
<!-- The script below helps to keep in memory the dropdown value after the page has been refreshed -->
<script type="text/javascript">
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
</script>
I think you should check if SessionStorage Key exists or not.
I have created working example of your code : https://jsfiddle.net/vieckys/Lwv1n8p7/7/
Here is HTML Markup:
<select name="options" id='dropdown'>
<option value="0" selected>--- select here ---</option>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
and JS Code
let selectedItem = sessionStorage.getItem("SelectedItem");
if (selectedItem) {
$('#dropdown').val(selectedItem);
} else {
$('#dropdown').val(0);
}
$('#dropdown').change(function() {
let dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
Let me know if you face any issue with this.
Based on your scenario, you can explicitly trigger the change event after the value is set for the dropdown using trigger('change') on the select dropdown. This will run the change function and will save the initial value in the sessionStorage. So, add this line of code, $('#dropdown').trigger('change') something like:
<script type = "text/javascript" >
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
$('#dropdown').trigger('change'); // trigger the change explicitly
</script>
I don't have much experience with JavaScript. Just PHP. I've been trying to create a JavaScript form that doesn't capture any information. It just redirects the user to a URL based on the State they select in a dropdown.
So if the user enters Alabama in the State dropdown list they get redirected to a set URL. So the code would have 50 URL possible redirects - one for each State.
I've been searching high and low and every attempt I make is horrific - if anyone has any advice on how to this it would be much appreciated.
<select class="form-control" name="stateId" id="stateId">
<option value="" selected="" disabled="">Select Country</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
$('#stateId').change(function(){
// get dropdown value to variable
var ID = $(this).val();
// redirect user with following dynamic url
window.location.href = "localhost/view/steteID/" + ID;
// or
window.location.href = "../view/steteID/" + ID;
// this is optional, if you required ajax call in future
$.ajax({
type: "get",
dataType: "json",
url: 'path/'+ID,
success:function(response){
$('#districtId').empty();
response[0].subProducts.forEach(function(elem,index){
$('#districtId').append('<option value="'+ elem.code +'"></option>');
});
},
error:function(xhr){
console.log(xhr);
}
});
});
You can write a method which will be fired upon the change of the select drop down and according to the value you can redirect the user.
Here is a PURE JAVASCRIPT implementation.
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="states_select"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
if(!event.target.value) alert('Please Select state');
else{
alert('You like ' + event.target.value);
//handle the redirect here
// window.location = "YOUR_REDIRECT_URL";
}
}
<select name="states_select">
<option> Select a State </option>
<option value="State 1"> State 1 </option>
<option value="State 2"> State 2 </option>
<option value="State 3"> State 3 </option>
</select>
Read more about the change event here
$(function() {
$('#websites').change(function() {
this.action = document.getElementById('urls').value;
this.submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="websites" >
<select id="urls">
<option value="https://google.com">Google</option>
<option value="https://stackoverflow.com">Stack overflow</option>
<option value="https://example.net">Example net</option>
</select>
</form>
Here you can achieve this
i have this drop down in html which is created by java script i need to fetch value from these dynamically created down with the same or id and and post it to through ajax in php can you please help how to get value from these selected drop down
<select name="criteria[]">
<option value="null" disabled selected>- select -</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<select name="criteria[]">
<option value="null" disabled selected>- select -</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
so what you can do is loop through the select list using jquery .each() and store the values in the array.
here's what you can try.
$(function(){
var array = [];
$('#btnGetVal').on('click', function(){
$('select[name="criteria[]"]').each(function(){
console.log($(this).val());
array.push($(this).val());
});
console.log(array);
$.ajax({
type: 'post',
url: 'yourfile.php',
data: {values:array},
success: function(d){
// do something on success
}
});
});
});
here's a working JSFIDDLE. Please check the console for values. Hope this helps
Your question is not completely clear. You have two identical dropdown controls, with identical names/options. Is this intentional? How do you wish to use them?
If both are required, it is a good idea to make them unique by assigning each a unique ID:
<select id="s1" name="criteria[]">
...options...
</select>
You can then access their data easily:
var sel1_val = $('#s1').val();
Because the HTML is created by javascript, you may need to use event delegation:
$(document).on('change', 'select[name="criteria[]"]', function(){
var sel1_val = $('s1').val();
var sel2_val = $('s2').val();
$.ajax({
type: 'post',
url: 'your_php_ajax_processor_file.php',
data: 'sel1=' +sel1_val+ '&sel2=' +sel2_val,
success: function(d){
if (d.length) alert(d);
}
});
});
In your PHP file:
<?php
$s1 = $_POST['sel1'];
$s2 = $_POST['sel2'];
//now, do what you need to do with the two values
The .on() is necessary to detect events for injected markup.
Note that if you are using AJAX (you are), then you don't need to use a <form> structure -- you can just use a normal div.
See these additional posts for more on AJAX:
AJAX request callback using jQuery
I was wondering if it is possible to change a value of a dropdown box dynamically and to trigger an ajax onchange function assigned to this dropdown at the same time.
so far I can only change the value of a dropdown box but the onchange function is not being called.
here is the dropdown:
<select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
<option value="">--Select Item--</option>
<option value="one"> Option one</option>
<option value="two"> Option Two</option>
<option value="three"> Option Three</option>
</select>
when I do this operation:
document.getElementById("ProductSelector").value = "one";
the value of the dropdown is changing, but the getItems function is not being triggered.
What am I doing wrong or may be there is another way to change a value of the doropdown which will allow me to trigger my ajax function as well?
I don't want to use JQuery. I just wandering why the function is not working if I use dinamic change and on manual change it works fine?
So, you are changing the value with JavaScript and the change event isn't triggering. So, lets trigger it then.
Trigger the event change every time you change the value via JavaScript.
No jQuery used.
Try this:
function changeVal() {
var elem = document.getElementById("ProductSelector"),
event = new Event('change');
elem.value = "one";
elem.dispatchEvent(event);
}
function getItems(val) {
alert(val);
}
changeVal();
<select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
<option value="">--Select Item--</option>
<option value="one">Option one</option>
<option value="two">Option Two</option>
<option value="three">Option Three</option>
</select>
I mostly do it this way:
HTML:
<select class="class-name">
<option value="1">1</option>
<option value="2">2</option>
</select>
jQuery:
$(".class-name").on("change", function() {
var value = $(this).val();
$.ajax({
type: "post",
url: "your-php-script.php",
data: { 'value' : value },
success: function (data) {
alert('This has changed');
}
);
});
Problem is changing the value with JS will not trigger the change event. Best solution would be to write a function which changes the value and triggers the change event manually.
HTML
<select name="ProductSelector" id="ProductSelector">
<option value="">--Select Item--</option>
<option value="one"> Option one</option>
<option value="two"> Option Two</option>
<option value="three"> Option Three</option>
</select>
JS (no jQuery)
//define the element so we can access it more easily
var element = document.getElementById('ProductSelector');
//define the event we want to trigger manually later
var event = new Event('change');
//add eventlistener which is triggered by selecItem()
element.addEventListener('change', function(event) {
getItems(event.target.value);
});
function getItems(val) {
alert(val);
}
//set the value and trigger the event manually
function selectItem(value){
//select the item without using the dropdown
element.value = value;
//trigger the event manually
element.dispatchEvent(event);
}
//using a function with the option you want to choose
selectItem("three");
JSFiddle
Use the working JSFiddle: Note that you have to uncomment the last line of code.
<html>
<body>
Select your favorite value:
<select id="mySelect">
<option value="value1">value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
<option value="value4">value4</option>
</select>
<script>
$(document).ready(function() {
$( "#mySelect" ).change(function() {
var value = $(this).val();
$.ajax({
type: "post",
url: "request-url.php",
data: { 'value' : value },
success: function (data) {
alert('the ajax request has been send');
}
);
});
});
</script>
</body>
</html>
You can try removing the onchange="" attribute from the select input and just use the jQuery to check for changes:
$('body').on('change', "#ProductSelector", function(){
var id = $(this).val();
//now do your ajax call with the value selected
});
"What am I doing wrong or may be there is another way to change a value of the doropdown which will allow me to trigger my ajax function as well?"
Another way of adding the event listener is by doing it "unobtrusive style".
document.getElementById('ProductSelector').addEventListener('change', function(event) {
getItems(event.target.value);
});
function getItems(val) {
// Todo: whatever needs to be done :-)
alert(val);
}
<select name="ProductSelector" id="ProductSelector">
<option value="">--Select Item--</option>
<option value="one">Option one</option>
<option value="two">Option Two</option>
<option value="three">Option Three</option>
</select>
http://jsfiddle.net/dytd96cb/
We have the following SELECT combobox that is populated dynamically with ajax and httphandler web service (.ashx).
When SELECT combobox is dynamically populated, it looks like this:
<select name="selectid" id="selectid">
<option value="">-Select an option-</option>
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</o4tion>
<option value="4">Test5</option>
<option value="5">Test6</option>
<option value="6">Test7</option>
</select>
Below is the js:
function getText() {
$.ajax({
url: 'rulings.ashx',
dataType: 'json'
})
.done(function(textInfo) {
$(textInfo).each(function(i, texts) {
$('<option>').val(texts.dbtextID).text(texts.textToBeDisplayed).appendTo( $('#selectid') );
})
});
}
When we display the values from the dropdown, it displays the VALUE options instead of the displayed text.
Example from the combobox above, it displays 1 instead of Test1.
How do I modify the script to show displayed text instead of VALUE options?
Try this code , just put it inside
$(document).ready(function(event){
$("#selectid").on('change',function() {
//alert($("#selectid option:selected").text());
$('#summTextvalue').html($("#selectid option:selected").text());
});
})
The ON method in jQuery can bind events to dynamically created elements.
or you can also do something like
function _bindEvent()
{
$("#selectid").on('change',function() {
alert($("#selectid option:selected").text());
});
}
and call _bindEvent() from your AJAX done method
Try this to get text, instead of value.
$('#selectid').change(function(){
var selectedVal=$(this).val();
alert($(this).children("option[value='"+selectedVal+"']").text());
});