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

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'));
}});

Related

Hide text before dollar sign character in options without removing completely

I am trying to find a way to select part of the string before the dollar sign in the select menu. Right now I am just trying to hide it so it does not appear in the dropdown, but it will be used later so I do not want to simply strip it out because I will need to be able to use it in a variable when the option is selected.
var seminiars;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select>
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
</select>
So far I have only been able to remove it completely, but then I was unable to store it and use it when someone selects on of the option.
Side note: I am unable to edit the html directly, the code is automatically generated.
okay... I just noticed the side note.
I am unable to edit the html directly, the code is automatically generated.
The trick here, will be to set a data value for each option.
// Run that loop to set the data values for each option
$("select option").each(function() {
let optionText = $(this).text();
let textSplit = optionText.split("$")
$(this).data("before_dolard_sign", textSplit[0])
$(this).text(textSplit[1])
})
$("select").on("change", function() {
// So on change, you have access to it
console.log($(this).find("option:selected").data("before_dolard_sign"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select>
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
</select>
You can use the value attribute to store more information not in the text visible to the user. I've added some code below to show how you can get the text or value selected by the user.
If that isn't suitable I've also created a test input and button which helps demonstrate how you can split a string in the way you need to.
The code is fully commented.
Let me know if you were hoping for something else.
// Detect when user changes select option
$("#selectTest").change(function() {
// Get the text selected by the user
console.log($("#selectTest option:selected").text());
// Get the value selected by the user
console.log($(this).val());
});
// Add click event
$("#splitButton").click(function() {
// Get input value
var test = $("#splitTest").val();
// Split around dollar sign
var els = test.split("$");
// Print values to show we did it correctly
console.log(els[0]);
console.log("$" + els[1]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="selectTest">
<option value="1$5,000">$5,000</option>
<option value="1$5,000">$10,000</option>
<option value="5$100,000">$100,000</option>
<option value="10$500,000">$500,000</option>
</select>
<input id="splitTest" value="10$500,000">
<button id="splitButton">Show Split</button>
why not place this data onto a data-meta attribute?
instead of
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
perhaps
<option data-meta="1">$5,000</option>
<option data-meta="2">$10,000</option>
<option data-meta="5">$100,000</option>
<option data-meta="10">$500,000</option>
then you can find the selected option and use element.getAttribute("data-meta") to retrieve the data when you need it
edit: i now see your side-note that you can't edit the html. well, replace it. loop over the html, and use .split on the textContent, and move that meta data into an attribute
Use the data attribute to store the info and then run an event listener to retrieve the dataset when selected on change?
const select = document.querySelectorAll('#money');
select.forEach((val) => {
if (val.value != 'undefined') {
val.addEventListener('change', () => {
let data = val.options[val.selectedIndex].dataset['num'];
console.log(data)
})
}
});
<select id="money">
<option style="display: none;">-->Select an option below<--</option>
<option data-num='1' class='opt' value='5000'>$5,000</option>
<option data-num='2' class='opt' value='10000'>$10,000</option>
<option data-num='5' class='opt' value='100000'>$100,000</option>
<option data-num='10' class='opt' value='500000'>$500,000</option>
</select>

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.

Grails if checks html select value

I have a problem with checking the select/grails select tag value via grails if tag. My code looks like this,
html:
<select id="select1" name="select1">
<option value=2>2</option>
<option value=3>3</option>
</select>
or grails select:
<g:select id="select1" name="select1" from="${[2, 3] }" value="2"/>
and the grails if:
...
<g:each var="rowNumber" in = "${0..5}">
<g:if test="${rowNumber} < ${select1.value}"> <!-- or ${select1.val()} or select1.value -->
...
</g:if>
</g:each>...
Code throws an NullPointerException, and says that select1 is a null object and he cannot evaluate method val(), or cannot get attribute value.
Anyone have an idea what I should do to fix this problem?
Thanks for help!
EDIT
Inside my if statement I have a render template, and when I change the value of select I want to render this templates again, but with saving what I have already type there (e.g if I have a textfield in my template).
EDIT2
I messed up a little bit. I want to create a dynamic table, e.g at start it could have 2 rows & columns, then I want to be able to enlarge/decreasenumber of rows/columns (e.g. by clicking button/buttons) of course by clicking the button, I want to save already filled table in ajax, then render table with new number of rows/columns, and fill earlier filled cell with their previous values (new cells will be empty).
e.g.
filled table 2x2
a a
a a
when I enlarge this table to 3x2 I want the table looks like this:
a a
a a
_ _
where _ is an empty cell.
Since you want to work on the client side you need to work with Javascript only.
function checkRows(rowNumber)
{
var value= $('#select1').val();
return rowNumber < elem;
}
If you want to trigger the function when the select value changes use
$(document).ready(function () {
$('#select1').change(function() {
checkRows(34 /* use your value here */);
});
});

Getting an option text/value with JavaScript

I am trying to build a form that fills in a person's order.
<form name="food_select">
<select name="maincourse" onchange="firstStep(this)">
<option>- select -</option>
<option text="breakfast">breakfast</option>
<option text="lunch">lunch</option>
<option text="dinner">dinner</option>
</select>
</form>
What I'm trying to do is send in the select object, pull the name and the text/value from the option menu AND the data in the option tag.
function firstStep(element) {
//Grab information from input element object
/and place them in local variables
var select_name = element.name;
var option_value = element.value;
}
I can get the name and the option value, but I can't seem to get the text="" or the value="" from the select object. I only need the text/value from the option menu the user selected. I know I can place them in an array, but that doesn't help
var option_user_selection = element.options[ whatever they select ].text
I also need to use the passed in select reference as that is how it's set up in the rest of my code.
Later on, that text/value is going to be used to pull the XML document that will populate the next select form dynamically.
You can use:
var option_user_selection = element.options[ element.selectedIndex ].text
In jquery you could try this $("#select_id>option:selected").text()
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text
form.MySelect.options[form.MySelect.selectedIndex].value

Selecting options from a drop down

I'm building a recipe-finder for a new food blog. The design I have basically involves the user selecting ingredients, one at a time, from a drop down <select>, the option disappearing from the list (so they can't select it again) and appearing on another HTML list with a link to remove it from the list. Once they're done, they click a button and that takes them through to a results page.
Here's the select markup as generated by the PHP:
<select>
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
It's not drastically complex but it does raise a few questions on how I'm going to do some of these things. I'm using jquery.
I need to store the selected items in memory so I know what to send to the search page when they've done selecting items. What's the best way of doing that in your opinion as each item has two values (its "real" value and its database-value)?
How do I make "Please select" the selected option after they've selected something (preferable without triggering the onchange event)?
Once I've stored it in memory and added it to the displayed list of things they're searching for, how do I delete that item from the available items? Can I just "hide" or disable it (safely)?
If in #3 I have to delete it from the DOM, when I add it again, can I sort the list (based on either value) and keep the please-select option at the top?
1.) You can append hidden form elements to the page whose value is the value of the selected option.
2.)
jQuery("#select-list")[0].options[0].selected = true // assuming it's the first item
3.) I would remove the element from the DOM using jQuery("#select-list option:selected").remove()
4.) You can use before(). jQuery(your_default_option).before("#select-list option:first");
You can store the 'two values' in a hidden form field as an object in JSON notation. This will make it easy to modify in jQuery as the user interacts with the page.
You will need to use a combination of the onchange, keyup and keydown event to capture possible changes to the form so that you can re-select the 'Please Select' option.
You will need to remove the option from the dom and re-add it later. You can easily do this through jquery through something like this:
$("select option:selected").remove();
You can write a sorting function for the options starting with index 1, and keep the 'Please Select' as the first option.
1)
Basic idea, you need to check to make sure the first is not picked
var selections = [];
var mySel = document.getElementById("mySelectId");
var ind = mySel.selectedIndex;
selections.push( mySel.options[ind].value ); //add to a list for you to remember
mySel.options[ind] = null; //remove
2)
mySel.selectedIndex = 0;
3)
See #1
4) Yes you can add it anywhere you want by using insertBefore
Example here: http://www.pascarello.com/lessons/forms/moveSelectOptions.html
Will leave this answer here but I think I failed to read your whole post, so it might not help much.
You need to give your select a id like this:
<select id="MySelect">
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
And to get it is just something like this:
<?php
$value = $_REQUEST["MySelect"];
echo $value;
?>
Code is not tested and $_REQUEST can be replaced by $_GET or $_POST regarding what you have specified as action on your form. $_REQUEST will eat it all though.

Categories