Post URL from multiple <select> elements - javascript

I have a page with isotope filter. It's using the combination filters with hash history. So whenever multiple filters are selected it updates the URL like this:
example.com/portfolio/#.filter1&.filter4&.filter6
Then I have a search form with multiple 'select' elements:
<form id="search-form" method="post">
<select>
<option value="filter1">Filter Name</option>
<option value="filter2">Filter Name</option>
<option value="filter3">Filter Name</option>
</select>
<select>
<option value="filter4">Filter Name</option>
<option value="filter5">Filter Name</option>
<option value="filter6">Filter Name</option>
</select>
...
<input type="submit" value="Search" />
</form>
I would like to combine the values from all the selected options of each 'select' element into the single URL and redirect to isotope ('portfolio') page with that combined value.
What would be the best way to achieve that? I'm unable to figure it out.

Try this in your js:
var data = { 'filters' : arrayHere };
$.ajax({
type: 'POST',
url: 'your url here',
data: data,
success: function(re) {
console.log('this is your return', re);
}
})
Make an array using $.each, and populate all values inside the array, then post it view ajax call.

1) Keep the selects out of the form and use IDs to access the selected values.
2) Create a hidden input field in the form
3) use onsubmit="mergeSelects()" javascript event.
4) create a function in js
function mergeSelects(){
//get all the values of selects
// append then and generate a string may be
var mergedStringVal = ""; // <--- store values here
// Set it in the hidden input field created in the form and submit them
document.getElementById("mergedSelects").val(mergedStringVal);
}

Related

remove the ? and name= in get method html

I made a quick code in html and js. The thing i want to do is via method get, to send the <select> into the url but without the ? symbol, and also the names in the select attributes. For example if I click the button, the url will appear
https://mytesting.com/?marca=HEREGOESTHESELECTEDITEM&modelo=HEREGOESTHESELECTEDITEM&ano=HEREGOESTHESELECTEDITEM`
What i want to do, is just to remove the ? and the names marca= &modelo= and &ano= and only show the selected items. For example:
`https://mytesting.com/Firstelement-Secondelement-Thirdelement
This is my html code
<form name="marcas" action="https://mytesting.com">
<select name="marca" onchange="relation()">
<option value="-">Marca</option>
<option value="vw">VW</option>
<option value="nissan">Nissan</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="buick">Buick</option>
<option value="chevrolet">Chevrolet</option>
</select>
<select name="modelo">
<option value="modelo">Modelo</option>"
</select>
<select name="ano">
<option value="ano">Año</option>
</select>
<button class="button1" id="send" type="submit" method="GET">Buscar</button>
</form>
And the javascript I made, just shows the corresponding items that are in an array.
You'll need to use JavaScript to intercept the submit event and craft the new URL
document.querySelector("form[name=marcas]").addEventListener("submit", (e) => {
e.preventDefault(); // stop the normal form submit action
const data = new FormData(e.target); // capture all the fields
const url = new URL(e.target.action); // start with the form action
// create the pathname by joining together all the field values
url.pathname = Array.from(data, ([_, val]) => val).join("-");
// now redirect to the new URL
location.href = url;
});

Add database default value to dropdown list using jQuery AJAX

I'm working with CRUD operation using jQuery AJAX and bootstrap modal in laravel. But the problem is when I want to edit something. I can't populate my dropdown list after an AJAX success request. How can I set database default value in my edit modal Dropdown List?
My Code:
$(document).ready(function() {
$('.acedit').click(function() {
$('#form')[0].reset();
$('#modal_form').modal('show'); // show bootstrap modal
var id = $(this).data('id');
$.ajax({
url: "{{route('academic.edit')}}",
method: 'post',
data: {
id: id,
'_token': "{{csrf_token()}}"
},
success: function(data) {
//$('#mycontrolId').selectmenu('refresh').val(myvalue).attr("selected", "selected");
$('.degree').val(data.degree).attr('selected', true);
$('.divison').val(data.division);
$('.year').val(data.year);
console.log(data); //{id: 2, user_id: 5, degree: "ssc", division: "First", year: "2009", …}
}
});
});
});
My Controller Method:
public function acadedit(Request $request){
$id=$request->id;
$info=Academic::find($id);
return $info;
}
My edit modal Dropdown list:
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>
There is no selected attribute on the <select> element, it's only for the <option>s. However, you don't really need it, because setting the value of the <select> element is enough to change the selection. But you need to match the value exactly with the proper letter casing, so all capital letters in your case.
Change this:
$('.degree').val(data.degree).attr('selected',true);
To:
$('.degree').val(data.degree.toUpperCase());
If you really prefer to do it with the attribute on the <option> instead of the value of the <select>, then you need to add the <option> to the jQuery selector like this:
$('.degree option[value=' + data.degree.toUpperCase() + ']').attr('selected', true);
Demo:
$('.degree option[value=SSC]').attr('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>
If you want to use response data from your Controller by Ajax, then it better to return it in Json format:
Use return response()->json($info); instead of return $info;
As I can see from your console.log output you receive degree: "ssc", whereas
your select option is SSC, so you need to uppercase the data before use it: $('.degree').val(data.degree.toUpperCase()); or to downcase values of select options: <option value="ss">SSC</option>.

Dynamically filled HTML select, change selected visual . Blade Laravel template

I have this code. I'm working in Blade template by Laravel framework.
<select class="form-control" name="id_zupanije" id="id_zupanije" onchange="popuniGradove(this, document.getElementById('id_grada'))">
#foreach($zupanije as $zupanija)
#if($zupanija->id == $idzupanije)
<option value="{{$zupanija->id}}" selected="selected">{{$zupanija->naziv_zupanije}}</option>
#else
<option value="{{$zupanija->id}}" selected="">{{$zupanija->naziv_zupanije}}</option>
#endif
#endforeach
<option value="0" selected="">--Odaberite--</option>
idzupanije is id of the select option that needs to be selected...
javascript function "popuniGradove" is for creating select options for another select.
What I want to know is how to visual update selected option, so when window loads I see created select and showing me selected option, not this one
"--Odaberite--".
EDIT
here is screenshoot of how it looks..
I have 3 selects.. first is Zupanija (eng. "province"), Grad (eng. City), Kvart (eng. quart).. when I select zupanija, select grad is filled with options -> cities that have foregin key id_zupanija in table .. samo for kvart, after city is selected, javascript creates options with proper kvarts
... After I press submit (bnt Filtriraj) I refresh the page and filter results below... but I want my selects to save their choosen options before before submiting.. they keep showing --Odaberite-- (default option, last created) afer submiting..
If I understand you right you could consider using a Package like the old laravel 4 FormBuilder.
E. g. https://github.com/kristijanhusak/laravel-form-builder
That way you can bind every form to the respective model like so:
{!! Form::model($user, array('route' => array('user.update', $user->id))) !!}
Laravel automatically checks if input is existing in cache and will attach that data to the form.
You have to add 2 selectize, in this example we have first one for states (for example) and a second one for cities (for example). when we select a state the page send an ajax request to fetch cities in this state, then we set cities list on the cities' select.
the state select :
<select id="select-cities-state" class="selectized">
<option value="1">State 1</option>
...
</select>
the cities select :
<select id="select-cities-city" class="selectized" disabled="">
<option value=""></option>
</select>
var xhr;
var select_state, $select_state;
var select_city, $select_city;
$select_state = $('#select-cities-state').selectize({
onChange: function(value) {
if (!value.length) return;
select_city.disable();
select_city.clearOptions();
select_city.load(function(callback) {
xhr && xhr.abort();
xhr = $.ajax({
url: 'https://jsonp.afeld.me/?url=http://api.sba.gov/geodata/primary_city_links_for_state_of/' + value + '.json',
success: function(results) {
select_city.enable();
callback(results);
},
error: function() {
callback();
}
})
});
}
});
$select_city = $('#select-cities-city').selectize({
valueField: 'name',
labelField: 'name',
searchField: ['name']
});
select_city = $select_city[0].selectize;
select_state = $select_state[0].selectize;
select_city.disable();

Put data into textboxes when item is selected in combobox

I have a combobox with a name and ID of "device". When a device is selected from the combobox e.g. "iPhone 1st Gen", I want a text field with a name and ID of "processor" to fill with the processor name e.g. "Underclocked 412Mhz".
How can I do this?
I can use HTML, PHP and Javascript.
You can do this using Ajax. The most easy way is making the AJAX request with jQuery.
Below an example:
Call a JavaScript function when the 'change' event ocurred on your combobox:
<select id="device" onchange="changeDevice(this.id);">[your options]</select>
Make an ajax request in your JavaScript method:
function changeDevice(deviceID){
$.ajax({
type:'post',
url:'[url of your php file]',
dataType:'text',
data:{device_id:deviceID},
success:function(response){
//assign the text response to your input text
$('#processor').val(response);
}
});}
You could fix this with plain old Javascript
<select name="combo">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="Duck">Duck</option>
<option value="Rabbit">Rabbit</option>
</select>
<input type="text" name="picked" id="picked">
<script>
document.getElementsByName('combo').item(0).onchange = function(){
document.getElementsByName('picked').item(0).value = document.getElementsByName('combo').item(0).value;
}
</script>

Sorting via dropdown and updating the querystring

For paging I have this code which enables me to update the querystring without losing any elements in the querystring.
var tRVD = new RouteValueDictionary(ViewContext.RouteData.Values);
foreach (string key in Request.QueryString.Keys)
{
tRVD[key] = Request.QueryString[key];
}
tRVD["page"] = #i;
#Html.ActionLink(#i.ToString(CultureInfo.InvariantCulture), "Index", tRVD);
I need to do the same with sorting. I have the following code but of course the querystring is overwritten by sortby. What I need is the same as I have for paging, something that just adds sortby to the querstring if it is not there and updates it if it is. How is this possible?
<form name="sortbyformtop">
<select onchange="location.href=this.options[this.selectedIndex].value" name="sortbyselecttop">
<option value=""></option>
<option value="sortby=accommodationtype">Accommodation type</option>
<option value="sortby=mostreviewed">Most reviewed</option>
<option value="sortby=lowestprice">Lowest price</option>
</select>
</form>
So, what I'm trying to achieve is setting the querystring to the same value as it is now plus sortby.
You need to add an <input type="hidden"> to your form for each value in the querystring.

Categories