Re-select option value after AJAX response - javascript

I have a pretty simple form I'm building out using PHP, AJAX and jQuery. The form consists of a select box of the existing people that is populated from the database. Underneath is common contact information (Address, City, Phone, etc.) When the page is loaded, the form is empty except for the select box containing the people.
The basic idea is that when the user selects a person, it should populate that person's contact info into the form. The form appears as a modal window, so I do not want the page to refresh, so I'm sending an AJAX request to the server passing the unique ID and in turn, the server responds with a JSON-encoded PHP array with that person's contact info. I am taking that information and populating the form.
All of this is working as I need except for the data that should go into select boxes (e.g. State). I am successfully retrieving the proper state value and have validated that value matches the options in the select, but I cannot get it to change the selected value in the select box.
Here are the highlights of my code:
<!-- abridged generated HTML -->
<select name="PersonID" id="PersonID">
<option value="1">Mike</option>
<option value="2">Jim</option>
<!-- etc... -->
</select>
<input type="text" id="City" />
<select name="AttState" class="selectpicker" id="AttState">
<option>State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<!--And so on... -->
</select>
<!-- etc... -->
And then the Javascript...
$(document).ready(function() {
// This will pre-select when the form is initially loaded
var selState = "TX";
$("#PersonID").on('change', function(e) {
personId = $("#PersonID").val();
$.getJSON('GetPersonInfo.php?q=' + personId, function(data) {
$.each(data, function(key, val) {
$("#City").val(val.City);
selState = val(val.State);
// Plus all of the others...
});
});
$("AttState").val(selState);
});
When the form initially loads, the State is getting preselected to Texas; however, when the person is chosen and selState changes (validated by an alert), it doesn't get set to the correct value. I have read some posts that seem to revolve around ensuring that the JavaScript code living inside of the $(document).ready(function() function, so I suspect that the AJAX call doesn't retrigger the function. I cannot figure out how to make it work.

You should placed this code $("AttState").val(selState); inside success callback of AJAX request like so :
$.getJSON('GetPersonInfo.php?q=' + personId, function(data) {
$.each(data, function(key, val) {
$("#City").val(val.City);
selState = val(val.State);
// Plus all of the others...
});
// its depend on your code whether inside .each() or not
$("#AttState").val(selState);
});

Related

Clear dropdown Select2 populated from JSP / Ajax with a button only works once

I have a page in which to make a query to the database, 12 filters are applied (each filter corresponds to a select2 dropdown).
When the page loads, the selects are filled by default with data from the java controller.
Example from a jsp page:
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
<option selected>All the results</option>
<c:forEach items="${fpaList}" var="fpaList">
<option><c:out value="${fpaList.fpaname}" /></option>
</c:forEach>
</select>
But, if the user selects any value in any of the filters, all the filters are updated based on the chosen selection, through an AJAX call.
For example, suppose we have two select filters (dropdown):
Select 1 (Animal group):
- Birds
- Mammals
Select 2 (Animal name):
- Parrot
- Dog
If the user chooses mammals, an AJAX function will be called that will query the database and update the content of the select 2, eliminating the Parrot option. (And so on with up to 12 filters).
The problem comes when I want to clear the applied filters and return to the original select content (the content that appears by default every time the page is loaded from the java controller).
I have tried many things, from similar Stackoverflow questions without success.
The last thing I tried was:
Save the initial content of the select in a variable:
const fpa = $("#selectFPA").find("option").clone();
Onclick event (Reset filters button)
$("#ResetFilters").on("click",function() {
//first we empty the content
$('#selectFPA').empty().trigger('change.select2');
//original value injection
$("#selectFPA").html(fpa),
$('#selectFPA').trigger('change.select2')
})
This works fine if I press the button once, if I press the button a second time, the selects randomly select different values by default and they behave strangely.
I know this is a very specific question, but could someone help me? What am I doing wrong?
Thank you.
I think as per this answer you cannot create constant in jquery that's the reason only first time it works and next time it doesn't .Alternate, solution might be assign that clone value to some div and fetch it anytime when needed.Like below :
//call when page loads for the first time
$(document).ready(function() {
//cloning
var fpa = $("#selectFPA").find("option").clone();
//assigning value to div
$("#abc").html(fpa);
$("#ResetFilters").on("click", function() {
//getting clone value from div
var c = $("#abc").find("option").clone();
//first we empty the content
// $('#selectFPA').empty().trigger('change.select2');
//original value injection
$("#selectFPA").html(c);
//$('#selectFPA').trigger('change.select2')
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
<option selected>All the results</option>
<option>1</option>
<option>2</option>
</select>
<button id="ResetFilters">Reset</button>
<div id="abc" style="display:none"></div>

how to pass selected value from dropdown to another dropdown in next page

I have a form when user select value from dropdown it can direct them to another page.but in the next page I want the selected value to be pass to another dropdown.
for instance: user select country; then go straight to the next page where there is a dropdown already selected the country value. then only they can do the next process...
note:(list item in the dropdown is same as the 1st)
hope anyone can help me.
thanks.
Simply you can store the first-page dropdown values in Session or Cookies. If you have less important things like country, cities, and address locations then you can simply use the Cookies to store the data.
You can use url parameter to pass the selected value from one page to another.
http://www.test.com/next_page.php?selected_value=12
Like above example you can pass the selected drop down value to another page in php.
You can use
$_GET['selected_value']
in next page to get selected value.
You have to get select value by doing onChange event via jquery.
After jquery, you need to pass that value to particular change event.
Lets say you have this select box
<select id="select1">
<option value"">Select</option>
<option value"1">A</option>
<option value"1">b</option>
<option value"1">C</option>
</select>
While if any value changes you need to navigate to that page taking that option value.
So this is how you can do it via jquery.
$("#select1").change(function(){
//alert();
var changedval = $(this).val();
var url = "pagename/countryname="+changedval;
window.location.href= url;
/* $.ajax({
url: url,
type: 'GET',
data: {'image_name': image_name, 'id' : id},
success: function (data) {
$("#profile_picture_display_outer").hide();
},
error: function (data) {
}
}); */
});
You can even get values via ajax as well or you can directly redirect to that particular url via appending current selected value.
Additional if you are using Codeigniter 3 then this is how you can mention routes in routes.php
$route['pagename/(:any)'] = 'Controller/methodname/$1';

Google Script - Form - live update for a text field

My client has a huge list of contacts.
I created a form with a scrolling list, in order to select a contact. The issue is that the scrolling list is too long.
Is there a way (and if so, how?) for my client to start typing the first letters of a contact name, so the 'field area' (or other) fills in automatically the correspondant contact name?
Thank you in advance for your help.
Kind regards,
You can load the select with this javascript:
function updateSelect(vA)
{
var select = document.getElementById("sel1");//or whatever you select id is
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
The html select element:
<select id="sel1">
<option value="" selected></option>
</select>
I often load selects when the page loads with something like this:
$(function(){
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();//a gs function which passes an array to updateSelect via the success handler
});
That way I can use a spreadsheet to store the values that I want. In your case you may want to filter them alphabetically perhaps. And you might want to pass the getSelectOptioptions() function or whatever you call it a parameter to determine how to filter the list.

jQuery validate max value on Form Submit

I want to validate a form, when it gets submitted. I need to check the following things:
Whether the user has selected any option from the dropdown.
Whether the user has entered a value larger than the max-value
If any of this conditions is not matched, I want to show an error message in a modal window...
How can I achieve this behaviour? Below is a code snippet:
//This function sets max value, based on selected option's data-max
$('select').change(function(e) {
var selectedIndex = $('select').prop("selectedIndex");
var selectedOption = $('select').find("option")[selectedIndex];
$('input[type=number]').attr('max', $(selectedOption).data('max'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="./cart_update.php">
Select Size:
<select size="1" name="options" class="selectsize">
<option value="">-- Select --</option>
<option value="30" data-max="50">30</option>
<option value="31" data-max="50">31</option>
<option value="32" data-max="40">32</option>
<option value="33" data-max="50">33</option>
<option value="34" data-max="50">34</option>
</select>
Quantity
<input type="number" class="cart_qty" name="product_qty" size="1" value="1" min="1" max="100" />
<button class="orange medium full add-to-cart" type="submit">Add To Cart</button>
</form>
As you didn't give any information on whether you validate the form data within the backend as well, I assume that you don't.
Validating form data only on the client side (i.e. within the client's webbrowser) is not advisable. That is because clients can easily manipulate the javascripte code you're using to validate data. By doing so, it is possible to import fraudulent data into your application (and many many more bad things could happen).
Validating data on the client side should only be used to give your users a quick feedback on whether the entered information is correct and in accordance to your definitions. Real data validation, before you further use it within your application (i.e. store it within a database, or what ever), should happen on the server side.
I advise you reading these articles to further deep dive into the topic of data validation:
Data form validation (mozilla.org)
If you're using PHP as a server-side language: PHP 5 Form Validation (w3schools.com) or if you're using javascript as a server-side language: How to Easily Validate Any Form Ever Using AngularJS(thecodebabarian.com)
Web Form Validation: Best Practices and Tutorials (smashingmagazine.com)
Coming to your question (and assuming you read the articles and now want to validate the data only for the user's sake), here's kind of a commented working code snippet:
$(document).ready(function () {
// Whenever your form is submitted, execute this function
$('#ourForm').submit(function (e) {
// Prevent the browser from executing the default behaviour -> submitting the form
e.preventDefault();
// Now check the user's entered information for accordance to your definitions
// #1: Check whether any checkbox is ticked
var checkBoxValue = $('#ourCheckbox').val();
// If checkBoxValue is undefined, there is no checkbox selected,
if (!checkBoxValue) {
// There is no checkBox ticked, throw error
alert('Please select a checkbox!');
return false;
}
// #2: Check whether entered value is smaller than the data-max field of the selected checkbox
// Receive the user's entered value
var enteredValue = $('#ourInputfield').val();
// Receive the max value specified by you from the data-max field
var maxValue = $('#ourCheckbox option:selected').attr('data-max');
// If the entered value is bigger than the max-data value
if (enteredValue > maxValue) {
// The entered value is bigger than the data-max field of the selected checkbox, throw error
alert('Your entered value is to large, please choose a value lower than ' + checkBoxValue.value);
return false;
}
// Validating your form data is finsihed, go on with the real work
alert('Your data looks fine, whoooo!');
});
});
Here's a working JSFiddle: https://jsfiddle.net/77v1z18v/1/

How do I refresh an html element?

I've tried searching for any possible solutions to my question but none of what I've seen so far works. Anyway, I'm using MVC 3 and I have a form called Add Event. On that page, I have a dropdownlist that contains a list of locations that the user can choose from. I have a link just below that dropdownlist that would allow a user to add a new location. Now, I have the textboxes, dropdowns, etc for creating a new location in a partial view which would appear below the dropdownlist when I click on the link.
Anyway, I need to refresh, just the dropdownlist so that when I add a new Location, it goes right on the list. What happens right now is after I click on save, the partial view hides itself and I still need to refresh the entire page to get the new location on the dropdown list which would then, remove everything I typed in on texboxes and dropdownlists on the same page.
How can I do this using javascript/ajax?
With jQuery you can reload only the element you want:
$('#menu').load("myServerScript.php #menu");
http://api.jquery.com/load/
This might help you..
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = Text;
opt.value = Value;
// Add an Option object to Drop Down
document.getElementById("YourDropDownID").options.add(opt,null);
this can be done with jQuery.
My way of doing it would be like this. Assuming that you have a form that looks something like this:
<form method="post" action="#">
<select id="myList" name="myList">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
<input type="text" id="newValue" name="newValue" />
add new value
<input type="submit" value="Submit">
</form>
Where myList is dropdown you want to add a new value and refresh, newValue is the text field to receive the new values to be added to the dropdown (myList) and the link with id btn is the add button. You can add a jQuery that would look something like this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function (event) {
event.preventDefault();
$.post("/home/addvalue", { value: $("#newValue").val() }, function (result) {
if (result != null) {
$("#myList").append("<option value='" + result.id + "' selected='selected'>" + result.text + "</option>");
}
});
});
});
</script>
What I'm is when you click on the link (btn) I collect the value (and just that value) from the text box and do POST (a form submit) to the server.
I'm guessing you're expecting the server to give some sort of answer that includes the newly inserted value's id.
If the server sends back that new id, I then append the the new result to list (and set it as the selected one)
On the server side you code could look something like this
[HttpPost]
public JsonResult AddValue(FormCollection collection)
{
//do database inser for the new value and get the id
var response = new Dictionary<string, object>();
response.Add("id", 3);//3 here represents that last id
response.Add("text", collection["value"]); //the value you sent for the new option
return Json(response);
}
you receive the the POST(ed) data and do save to the database. Once the value is saved and you have the new id save in into a dictionary that you'll then serialize and send back as json the javascript above.
This would update your form, so you when you actually hit submit myList value would be the new value.
Hope this helps (and if does, please accept the answer)

Categories