Javascript to pass var onclick select and checkbox - javascript

So my page has two columns. On the right column the results are displayed.
The results include all the elements. On the right column i have a and few check boxes. I am able to populate the checkboxes depending on the option selected in .
I have to click submit to get the data on the right column. I don't want AJAX. I want the page to be refreshed with the option in selected and the results to be displayed based on that. I am able to code the php part. To GET the value of the option selected in
So my code is :
<select id="theselect" onclick = "afterChange()">
<option value="0"> Select the Department </option>
<option value="11"> Department11 </option>
<option value="22"> Department22 </option>
<option value="33"> Department33 </option>
</select>
var url = location.href;
document.getElementById("mydiv").innerHTML = url;
function afterChange(){
var dept = document.getElementById("theselect").value;
if (dept && dept!= 0) {
var myline = url + "&dept=" + dept;
document.getElementById("mynewdiv").innerHTML = myline;
window.location= myline;
}
}
<p id='mydiv'> </p> <br />
<p id='mynewdiv'> </p>
<?php
if(isset($_GET['dept'])) {
$cat = $_GET['dept'];
echo "You are now searching in $cat";
//code to show content from database for that department
?>
I know that there is a better way to do this which m unaware of. So far the code works fine for the first time. I am able to get the results from the DB according to the SELECT option.
But when i change the select, it takes the entire URL again and adds the new value of SELECT to the URL, that confuses PHP.
So if my site URL is :
http://mysite.php?dept=22
After changing SELECT 2nd time, it changes to
http://mysite.php?dept=22&dept=33
I also have few checkboxes after the SELECT.
I want the results to be sorted based on the select and the checkboxes.
I know there must be an easy way to do it, but i am struggling to find it.
Please help me in understanding this concept. Thank you so very much.

With
var url = location.href;
You will always get the current url. Means on 2nd refresh the url will be http://mysite.php?dept=22 now you add your dept again:
var myline = url + "&dept=" + dept;
Which produces the error you described.
To handle this problem you have to strip the old parameter first or if you only need one parameter do something like:
var url = location.origin + location.pathname
instead of location.href for more information you can read this

Related

Javascript change currency always choosing first <option> from <select> dropdown list

Hi I've been modifying a script that got the data from <span id=> to instead use a <option value=> from a dropdown list and it seems to work except for always choosing the first <option value=> in the list. If i arrange the order of the html list the first currency will be what it converts to onChange.
Here is the script and html
function ChangeCurrency() { $('select').click(function () {
var cc = $(this).children('option').attr('value').substring(1);
document.cookie = 'CurrencyId=' + cc + ';path=/';
var s = location.pathname;
if (s.length > 3 && s.substring(3, 4) == '/')
s = s.substring(3);
location.pathname = s;
})};
<select onchange="ChangeCurrency()">
<option value="c1">USD</option>
<option value="c2">EUR</option>
<option value="c3">AUD</option>
etc...
</select>
I don't know what I'm doing wrong? How can I get it to actually process a user selected option from the list (and hopefully keep that option displayed so the list doesn't show USD when the currency on the store is changed to AUD for example)
EDIT:
I need to keep how this code gathers data to "build" the cookie, I don't understand enough to know what string it is putting together from the option list to name the cookie but it is important for the store currency to work. This is the code that worked but the list was a div with span id for the option value. It took me a while to get it sort of working using option values rather than span id's except for being stuck on the first option in the list.
Your code just fetches the first option, not the selected one.
Change the:
var cc = $(this).children('option').attr('value').substring(1);
to:
var cc = $(this).val();

html Select not saving data after history.back() is callled

I am building a form using phpmailer, witch consists of 3 steps: the form itself, information confirmation page and mail sent message page. When the user is on the information confirmation page, he is able to go back and correct the information that was written, by busing onclick="history.back();". Everything is working fine, all fields remain written as the user did, with exception of a select button for years that is using the following code:
<select id="f_year" name="f_year" data-validation-engine="validate[required]" class="validate[required]"></select>
<script>
var start = 1900;
var end = new Date().getFullYear();
var options = "<option disabled selected value>年</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year + "年" + "</option>";
}
document.getElementById("f_year").innerHTML = options;
</script>
When its clicked to correct the information, the data from this select element is not saved at all.
What should I do?
Check the following out. This is a Minimal, Complete and Verifiable Example of your problem scenario.
As you can see, there are two SELECT elements, that one is hard-coded and the other is dynamically generated (the same script that you have provided).
<html>
<body>
<select>
<option value="Val1">V1</option>
<option value="Val2">V2</option>
<option value="Val3">V3</option>
<option value="Val4">V4</option>
<option value="Val5">V5</option>
</select>
<select id="f_year" name="f_year" data-validation-engine="validate[required]" class="validate[required]"></select>
<script>
var start = 1900;
var end = new Date().getFullYear();
var options = "<option disabled selected value>年</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year + "年" + "</option>";
}
document.getElementById("f_year").innerHTML = options;
</script>
<button onclick="window.location='confirm.php'">Proceed</button>
</body>
</html>
When you try running this, you'd see that the hard-coded one stays intact, while the dynamically generated one resets, when you navigate back to the same, from the confirm page.
What happens is, when you navigate back, the scripts on the page will execute from the beginning, changing the values, hence the dynamically generated inputs will be reset. Only the static content could be kept intact. To keep the dynamic stuff intact, you will need some extra work.
This question looks similar to your problem scenario, which is suggesting something for those extra work you need to do to preserve the dynamic content.

How to set listing number of items per page and setting selected option on click

How do I set listing number of items per page, removing/adding URL parameter and setting selected option all on click?
I'm working on a drop down for a search page which will allow users to select how many items they'd like to view per page. When the user click on an option, the parameter &itemSize=*option value* needs to place itself in the URL.
This part I have down just fine. The problem is if the URL already has for example &itemSize=60 and the user chooses to go to 90 items, I need to replace the current parameter. Either replace its value or delete it all together and then replace it with a new &itemSize= parameter. What I'm getting right now is a doubling of parameters - &itemSize=60&itemSize=90
Also I can't get the selected option to switch since I'm not sure how to store the value of option selected.
Note - the page is reloading each time the option is chosen. It's not done over AJAX and currently that's not an option. Cannot use a plug-in. Search results can be as high as 3000 results. I have code that I thought would work for taking care of the duplicaate parameter situation, but I have no idea how to go thru the logic for a new selected option.
function js_sort(forms, type) {
var currentURL = window.location.href;
if (type == 1) {
var url = window.location.toString();
if (url.indexOf("&rows=") > 0) {
var clean_url = url.substring(0, url.indexOf("&rows="));
window.history.replaceState({}, document.title, clean_url);
}
location.href = clean_url + forms.value;
} //else if () {
//dont mind this, this is part of a diff drop down
//}
}
<div class="dropdown">
<select name="pagesize" onchange="js_sort(this,1)">
<option value="30" selected>30 Items Per Page</option>
<option value="60" selected>60 Items Per Page</option>
<option value="90" selected>90 Items Per Page</option>
<option value="120" selected>120 Items Per Page</option>
</select>
</div>
for the next readers to find the solution
note: updated to a more generic form
window.location.href= window.location.href.replace(/&*itemSize=\d*/,'')+"&itemSize="‌​+forms.value;

Combining javascript and jquery to fill multiple hidden fields - bad idea?

I'm trying to find the best way to make my teachers' lives a little easier.
I've got a select field and list of options generated by a tlist sql query. The select field itself already has a javascript attached to it, which fleshes out other field values (credit values and credit types) elsewhere based on the id of the select option chosen. This is the javascript that works for that purpose:
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('courseno').value;
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
}
</script>
I also need to populate a hidden field that is (and must remain) outside the tlist sql tag that generates the select list.
Here is my sql code:
<select id="courseno" name="course_number" onchange="changeValue();">
<option value="">Select a Course</option>
~[tlist_sql;
SELECT cc.course_number, cc.section_number, c.COURSE_NAME
FROM cc cc
RIGHT JOIN COURSES c ON c.COURSE_NUMBER = cc.course_number
RIGHT JOIN STUDENTS s ON cc.studentid = s.id
WHERE cc.studentid = ~(curstudid)
AND TERMID = ~(curtermid)
AND c.CreditType LIKE 'English%'
AND NOT EXISTS (
SELECT * FROM storedgrades sg
WHERE sg.studentid = ~(curstudid)
AND sg.course_number = c.course_number
)
ORDER BY c.course_name;]
<option name="~(course_no)" value="~(course_no)" id="~(secno)">~(course_no).~(secno) (~(cname))</option>
[/tlist_sql]
</select></td>
</tr>
And just below that is the hidden field I would like to populate:
<td width="25%" class="bold"> </td>
<td><input type="text" id="secnum" name="section_number" value=""> </td>
I gave each of the options the section number as its ID, thinking I could use the ID element of each of those options and some clever jquery to populate the hidden field, but I'm having no luck. I just read on another question that was ably answered by the community that you shouldn't use an option ID tag that begins with a number... so now what can I do?
Could somebody please help me?
Thanks forever,
Schelly
I don't think your problem comes from the ID being a number. We haven't seen what jQuery you've tried, but you most likely don't need jQuery at all. Assuming what you have is working correctly, and the PowerSchool code is putting out elements the way you expect them to be (View Source in your browser to be sure, if this doesn't work), you should be able to grab the ID from the selected option inside your changeValue function, store it in a variable, and push that value into the "secnum" field as follows:
function changeValue(){
var courseDropdown = document.getElementById('courseno');
var selectedElement=courseDropdown.options[courseDropdown.selectedIndex];
var option=selectedElement.value;
var courseNo = selectedElement.getAttribute("id");
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
document.getElementById('secnum').value=courseNo;
}
I changed the way that your "option" variable is being set, but it will work the same way. You might end up wanting to move the last line, where the "secnum" field is being set, or wrap it in an "if", etc.; I don't know your full requirements.
All that said, there would be nothing wrong with using jQuery in this situation, but it's not necessary in this case unless you need extreme backwards-browser compatibility.
Working Example Here
You can use multiple on change events to do whatever you want. On change add a new event and populate the hidden input. You can define custom attributes to any html element with any data that is required to populate the hidden input
<select id="myselect">
<option>Select</option>
<option data-number="1">One</option>
<option data-number="2">Two</option>
<option data-number="3">Three</option>
<option data-number="4">Four</option>
<option data-number="5">Five</option>
</select>
<input type="hidden" id="hiddenInput"/>
$(document).ready(function(){
$('#myselect').on('change', mySelectChange);
function mySelectChange(){
console.log('your standard change value here');
}
$('#myselect').on('change', mySelectChange2);
function mySelectChange2(){
var option = $("#myselect option:selected");
console.log(option.text());
console.log(option.attr('data-number'));
}});

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