html with many similar selects that react when changed - javascript

My html contains many similar selects which I thought I could do all as
<form name="form">
<select name="site" size="1" onChange="formHandler()">
<option value="$site?i=$i&j=$2">ABC</option>
...
</select>
</form>
Contained in the html header is
function formHandler() {
var URL = "";
URL = document.form.site.options[document.form.site.selectedIndex].value;
if ( (URL != "") && (URL != "0") ) {
window.location.href = URL;
}
}
But I get TypeError: document.form.site is undefined. I presume this is because the forms and their selects all have the same name. This is because I only want one formHandler() in the header.
Very thankful for help!

Pass the element as parameter to the handler function:
onchange="formHandler(this)"
and then in the handler:
function formHandler(el) {
var url = el.options[el.selectedIndex].value;
// and the rest...
}

Related

validating multiple controls in javascript

I am adding multiple controls on an .aspx page from the .vb page based on certain conditions.
My code looks like following:
Dim sb As New StringBuilder
sb.Append("<table border='0'cellpadding='0' cellspacing='0' width='50%' class ='tabledata' id='tblContent'>")
For Each item As myObject In myLst
sb.Append("<tr><td style='width:50%;' valign='top'>")
sb.Append("<textarea id=txt_comments" & i & " name='txt_comments' rows='5' cols='60'></textarea></td>")
sb.Append("<td style='width:15%' valign='top' align='center'><select ID = validate" & i & " name=ValidateValues style ='border:1;width:150px'><option value = ''>Select</option><option value = 'Yes'>Yes</option><option value = 'No'>No</option><br /><br /></td>")
sb.Append("</tr><tr>")
Next
sb.Append("</table>")
myContent.InnerHtml = sb.ToString
So here I am creating <textarea> and <select> dynamically and adding them to my div(myContent)
<div id="structuredContent" runat="server">
</div>
I have a button next where I need to validate for few conditions.
My validation rule is:
User has to select either yes or no from the dropdown(<select>)
If user select 'yes', they have to enter text in
<textarea>(minimum1 character, maximum 1000 characters)
If user select 'No', <textarea> should be disabled.
I am trying to validate like following:
function validateComments() {
var errorcheck = 0;
$("[id^=txt_comments]").each(function () {
var comment = $.trim($(this).val());
$("[id^=validate]").each(function () {
debugger;
var value = $(this).val();
if (comment == 0 && value == "Yes") {
debugger;
errorcheck = 1;
}
});
}); if (errorcheck == 1) {
//show error message
}
else {
ErrorHide();
return true;
}
}
I am able to validate only for one control(which is textarea) from the above code.
The textbox and respective dropdown should be validated along.
How do I add validation for dropdown and can I combine with in the same function.
Any help?
Thanks in advance.
I don't know how do you expect this like if (comment == 0) { to work.
You'll always get a string as a value and checking it with 0 would always return false. Rather you need to check it with "".
And to enable/disable textarea you'll have to attach an event to select tag and do whatever you want to do.
here is an example
$("#d").change(function(){
if($(this).val() === 'n'){
$("#t").prop('disabled', 'disabled')
}else{
$("#t").prop('disabled', false)
}
});
$('body').on('click', '#b', function() {
var text = $.trim($("#t").val());
if(text === "" && !$("#t").prop('disabled')){
alert("yo! not valid")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="d">
<option value="0">Select</option>
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<textarea maxlength="50" id="t"></textarea>\
<button id="b">Validate</button>

Pass the selected value in HTML <select> to a javascript variable?

I am trying to run the js script using the parameters specified on the webpage, when javascript is triggered, a php file will run. The expected output would be the result from getstats.php. It didn't work for some reason. Is it because app1 is not a global variable?
The HTML:
<select name="app" id="app1">
<option value=1>A</option>
<option value=2>B</option>
<option value=3>C</option>
<option value=4>D</option>
</select>
P1: <input type="text" id="p1">
Start Date: <input type="date" id="dt1">
End Date: <input type="date" id="dt2">
<input type="submit" id = "submit" value="Run"><br>
<script src="js/global.js"></script>
The javascript code in the global.js:
$('input#submit').on('click', function() {
var app1 = document.getElementById("app1").value;
var p1 = $('input#p1').val();
var dt1 = $('input#dt1').val();
var dt2 = $('input#dt2').val();
if ($.trim(p1) != '' && $.trim(app1) != '' && $.trim(dt1) != '' && $.trim(dt2) != '') {
$.post('getstats.php', {app1: app1, p1: p1, dt1: dt1, dt2: dt2}, function(data1) {
$('div#stats').html(data1);
});
}
});
Thanks for your help!
I think you forgot to use e.preventDefault in the click event.
If the form elements are inside a form, the button wil trigger the value passed to the form action attribute. This way the value will never be 'passed' to jQuery (JavaScript).
Also The click handler should be wrapped in a document ready function so it waits untill the DOM is ready before trying to bind the event.
$(document).ready(function() {
$('input#submit').on('click', function(e) {
e.preventDefault();
var app1 = $('#app1').val();
var p1 = $('input#p1').val();
var dt1 = $('input#dt1').val();
var dt2 = $('input#dt2').val();
if ($.trim(p1) != '' && $.trim(app1) != '' && $.trim(dt1) != '' && $.trim(dt2) != '') {
$.post('getstats.php', {app1: app1, p1: p1, dt1: dt1, dt2: dt2}, function(data1) {
$('div#stats').html(data1);
});
}
});
});
You can check values in firebug console with console.log('text'); or console.log(var);
Try to log app1 before you start the if statement to see if there is a value in the variable. If it prints undefined, maybe something else is wrong.
Have a look at this question, this question, this question, and this article...
You might also like to check out the .serialize() jquery function, which can help save you a lot of time, especially with validation. http://api.jquery.com/serialize/
hope this helps
I checked your code it's working fine :
Just write your code in
$(function()
{
// Your code
// This function is exceuted when page is loaded.
});
What I tried :
$(function()
{
$('input#submit').on('click', function() {
var app1 = document.getElementById("app1").value;
alert("--"+app1);// <------------ showing correct o/p
var p1 = $('input#p1').val();
alert(p1);
var dt1 = $('input#dt1').val();
var dt2 = $('input#dt2').val();
if ($.trim(p1) != '' && $.trim(app1) != '' && $.trim(dt1) != '' && $.trim(dt2) != '') {
$.post('getstats.php', {app1: app1, p1: p1, dt1: dt1, dt2: dt2}, function(data1) {
$('div#stats').html(data1);
});
}
});
});

link to selection of option selected

I have a form in contact page and three links suppose one, two, and three are in home page and I would like to link to contact page for each link but with one option is to be selected one and with two option is to be selected two and so on.
<select id="message_type" name="message_type" class="inputbox">
<option value="one">Suggestion</option>
<option value="two">Inquiry</option>
<option value="three">Offer</option>
</select>
when link one is clicked the contact page should show option selected one and the like.
How can I do that?
Edit
I have three links in home page
one
two
three
Now I want to show the contact page with option selected one for link one and so on...
here is the code which results the select
<?php
function dropdown($active){
$dropdown=array(
'option1'=>'Suggestion','option2'=>'Inquiry','option3'=>'Offers'
);
foreach($dropdown as $key=>$val){
$array[]=JHtml::_('select.option',$val,$key);
}
$dropdown = JHtml::_('select.genericlist',$array,'message_type','class="inputbox"','text','value',$active);
return $dropdown;
}
?>
and in the form
<form name="feedback" id="frmfeedback" action="" method="post" >
<div>
<label for="msg">Message Type: </label><span class="input"><?php echo dropdown(isset($post['message_type'])?$post['message_type']:'');?> </span>
</div>
.......
Can put a hash in the links on home page:
Make a Suggestion
Then on contact page:
$(function(){
var opts=['one','two','three'];
var hash =location.hash;// use browser location object to get hash
if(hash && hash !='#'){
hash= hash.replace('#','');
/* get index of hash from array*/
var optIndex= $.inArray(hash,opts);
/* if not in array value will be empty string, otherwise value of hash*/
$('#message_type').val( optIndx !=-1 ? hash : '' );
}
});
EDIT: If ID's are same as values on the links as shown in question
Can append the hashes to href on home page with:
$('#one,#two,#three').attr('href',function(idx, oldHref){
return oldHref +'#' + this.id;
});
EDIT: Using itemId in query string of url:
$(function(){
var opts=['477','478','479']; /* not sure these are accurate*/
var a = document.createElement('a');
a.href = location.href;
var ret = {},
seg = a.search.replace(/^\?/, '').split('&'),
len = seg.length,
i = 0,
s;
for (; i < len; i++) {
if (!seg[i]) {
continue;
}
s = seg[i].split('=');
ret[s[0]] = s[1];
}
var currVal=ret['itemId'];
if( currVal !=undefined && $.inArray(currVal,opts)>-i){
$('#message_type').val( currVal);
}
})
For different pages
var url= document.URL;
switch(url)
{
case 'http://jsfiddle.net/bs8dp/':
$('#message_type').val('one');
break;
case 'http://jsfiddle.net/bs66p/':
$('#message_type').val('one');
break;
default:
$('#message_type').val('two');
}
jsfiddle
OR
If you have options in same page then
('#your_tab_one').click(function(){
$('#message_type').val('one');
});
('#your_tab_two').click(function(){
$('#message_type').val('two');
});
('#your_tab_three').click(function(){
$('#message_type').val('three');
});

Append multiple dropdown values to URL

I'm trying to do something similar to this:
$('#dropdown1').change(function() {
window.location = $(this).val();
});
I need to build a page with 2 dropdown lists and a textbox, and I need the values for each one to be stored and then appended to the URL when the form is submitted.
The URL needs to look similar to this when all options have been selected:
http://www.domain.co.uk/search-results/?searchOptions=dropdown1=value1|dropdown2=value2|textarea1=value3
I've figured out how to store the values of the dropdowns but I can't seem to append it to the url.. Here's where I got to:
<script type="text/javascript">
function getValues() {
var priceTo = document.form.priceTo.value;
//alert (priceTo);
}
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo
return false;
});
});
</script>
<body>
<form id="form" name="form">
Price:
<select name="priceTo" id="priceTo" onchange="getValues()">
<option value="5000">Up to £5,000</option>
<option value="10000">Up to £10,000</option>
<option value="20000">Up to £20,000</option>
<option value="40000">Up to £40,000</option>
<option value="80000">Up to £80,000</option>
</select>
<input type="submit" id="submit" value="submit"/>
</form>
</body>
For some reason this goes to:
http://www.domain.co.uk/search-results/?searchOptions=priceto=[object%20HTMLSelectElement]
EDIT:
I finally got it working on most browsers, including IE8 with this code:
<script type="text/javascript">
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.selektvolvocars.co.uk/selekt-search-results/?searchOptions='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value + model.options[model.selectedIndex].value + '%7Czipcode=' +document.getElementById('zip').value + '%7Cproximitydistance=50'
e.preventDefault();
});
});
</script>
For some reason though it doesn't work in IE9... makes no damn sense to me, it just spits out a completely jumbled up URL. Any ideas?
your priceTo is the select list. Use the following to get the selected value:
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value
e.preventDefault();
});
If I've understood correctly:
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location = initialURL + $("#priceTo").val() + "|" + $("#anyOtherSelects").val();
e.preventDefault();
});
You can remove the rest of the Javascript.
You can use a little helper function which gets the id of a <select> or <input> element and returns it with its value. For example:
<script type="text/javascript">
//Helper function to return id and value. The id parameter shouldn't have the # sign at its beginning
function getIdVal( id ) {
return id + "=" + encodeURIComponent( $("#"+id).val() );
}
//run this when the document is loaded and ready
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?'
$('#form').submit(function(e) {
window.location.href = initialURL + getIdVal( "priceFrom" ) + "|" + getIdVal( "priceTo" );
return false;
});
});
</script>
Notes:
You get the value of the current <option> selected in a <select> element using $(...).val().
It is a good programming practice to use encodeURIComponent() for encoding the values just to make sure that no strange character is going to break your convention of using = and | as record and field separator in the search query URL.

Javascript: Show/Hide rows based on current value of drop-down

I'm working with Javascript and ASP in this scenario. When this particular page opens, one of my drop-down menus is already populated with a status of "Open" or "Closed" - you can see the value comes from an ID in my recordset.
What I would like to do now is this: If the status on the page when it first loads is "Closed" and the user decides to change it to "Open" they must re-enter a "Reopen Reason" - so, that would display the header and text box below the drop-down....
Here's what I have tried thus far: I have created a showHide() function and placed it inside of the select in the drop-down, but it doesn't do anything, so am now stuck. Any help is appreciated. Thanks!
<select name="cboStatus" id="cboStatus" style="width:200px" onchange="showHide();"> <%
RSStatus.MoveFirst
If Not RSStatus.EOF Then
Do While Not RSStatus.EOF
%><option value='<%= RSStatus("ID")%>'
<%If RSStatus("ID") = RS("prjStatus") Then Response.Write "selected"%>><%= RSStatus("prjStatus")%></option><%
RSStatus.MoveNext
Loop
End If
%>
</select>
The HTML that should be produced from the above JS:
<tr id="lbReopenReason" style="display:none">
<td bordercolor="#f0f0e4" bgcolor="#f0f0e4"><h3>Reopen Reason</h3></td>
</tr>
<tr id="trReopenReason" style="display:none">
<td bordercolor="#FFFFFF" bgcolor="#FFFFFF">
<input name="txtReopenReason" type="text" id="txtReopenReason" value="<%If (RS("reOpenReason")) <> "" Then Response.Write(RS("reOpenReason"))%>" size="100" />
</td>
</tr>
Javascript:
function showHide()
{
var cboStatus = document.getElementById("cboStatus");
var cboStatusValue = cboStatus.options[cboStatus.selectedIndex].text;
var lbReopenReason = document.getElementById("lbReopenReason"); var trReopenReason = document.getElementById("trReopenReason");
//If the status of the project is Closed at the time of page load, and that status changes, then the user must enter a re-open reason.
if ( (status == 3) && (cboStatusvalue == 'Open' )
{
lbReopenReason.style.display = "";
trReopenReason.style.display = "";
}
else
{
lbReopenReason.style.display = "none";
trReopenReason.style.display = "none";
}
}
Looks like there are two problems here:
1) Your function is called "statusShowHide()", not "showHide()", so that could be the reason it's not getting called.
2) Your onchange attribute is missing its closing quotes after the function call, so that could be it as well.
Give those fixes a shot and see if it works now.
EDIT: A few more suggestions:
In your showHide() method you say:
if ( (status == 3) && (cboStatusvalue == 'Open' )
when it should be:
if ( (cboStatus === 3) && (cboStatusValue === 'Open' ) )
Also, instead of the way you're currently getting the value of the element:
var cboStatusValue = cboStatus.options[cboStatus.selectedIndex].text;
Try using:
var cboStatusValue = cboStatus.value;
Have finally resolved this one with the following:
Window onload to populate initial record value:
window.onload = findStatus;
function findStatus()
{
var cboStatus = document.getElementById('cboStatus');
statusShowHide(cboStatus);
}
Followed by this Javascript for changing statuses:
function statusShowHide(obj)
{
var txtStatusFirstLoad = document.getElementById("txtStatusFirstLoad");
var lbReopenReason = document.getElementById("lbReopenReason");
lbReopenReason.style.display = "none";
if (txtStatusFirstLoad.value == 3 && obj.value == 1)
{
lbReopenReason.style.display = "block";
}
}
And added this hidden text box to capture initial status value:
<input name="txtStatusFirstLoad" id = "txtStatusFirstLoad" type="hidden" value="<%=RS("Status")%>" />

Categories