The user is to select gender.
HTML
<form ...>
<select id="id_gender" name="gender" onchange="hideMaidenName(this.value)">
<option value="M">Male</option>
<option value="F">Female</option>
<option value="U" selected="selected">To be defined</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js">
If gender is male, we warn the user that they must clear maiden name by hand. Then they may continue. But in this case we automatically change gender to 'U'.
Could you help me understand the situation.
In the console I have checked what I'd like to transmit into the production code.
In the console:
var gender = $('#id_gender')
gender
[<select id="id_gender" name="gender" onchange="hideMaidenName(this.value)">…</select>]
gender.val()
"U"
But when I use this code in production, I get exception that gender is not a function. I can make the code execute like this:
Working code:
var maiden_name = $('#id_maiden_name');
function hideMaidenName(gender) {
if ($('#id_gender').val() == 'M') {
if (maiden_name.val() != "") {
$('#id_gender').val('U')
alert("Clear maiden name!");
return;
}
}
}
</script>
And further goes my failure.
Not working code:
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
var maiden_name_row = $('#id_maiden_name_row')
function hideMaidenName(gender) {
if (gender.val() == 'M') {
if (maiden_name.val() != "") {
gender.val('U')
alert("Claear maiden name!");
return;
}
maiden_name_row.hide()
}
else {
maiden_name_row.show()
}
}
Half working code (reduced functionality as I failed to change the value of gender back to 'U':
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
function hideMaidenName(gender) {
if (gender == 'M') {
if (maiden_name.val() != "") {
alert("Claear maiden name!");
return;
}
}
}
The questions are:
What is the difference between $('#id_gender') and var gender = $('#id_gender'). I mean why the former is working perfectly whereas the latter throws an exception.
Why in the half working code gender == 'M' works perfectly? Gender seems to be an element whose value I'm going to check. But here we have value itself stored in gender.
I have the working code, but I look for the gender element twice.
How should I prevent double finding if possible?
You pass as argument to the function hideMaidenName the value of the selected option on change(this is the string for example 'M'). I changed it to pass the DOM element(select), by passing this as argument. You also have to wrap the gender and use it as jquery object for example $(gender) otherwise you get the error .val() is not a function:
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
var maiden_name_row = $('#id_maiden_name_row')
function hideMaidenName(gender) {
//here you have to use gender as jquery object
if ($(gender).val() == 'M') {
if (maiden_name.val() != "") {
gender.val('U')
alert("Claear maiden name!");
return;
}
maiden_name_row.hide()
} else {
maiden_name_row.show()
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="id_gender" name="gender" onchange="hideMaidenName(this)">
<option value="M">Male</option>
<option value="F">Female</option>
<option value="U" selected="selected">To be defined</option>
</select>
Instead of setting the value of the select field you could just set the option with the value U as selected manually.
$('select#id_gender option[value="U"]').prop('selected', true)
EDIT:
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
function hideMaidenName(gender) {
if (gender == 'M') {
if (maiden_name.val() != "") {
//selecting option with value "U"
$('select#id_gender option[value="U"]').prop('selected', true)
return;
}
}
}
EDIT2:
There is no difference. The difference is that you write the element into a variable to you don't need to search the DOM multiple times.
Ill try to answer the other questions later.
Related
WDrodownList
When I am selecting a value from dropdown list say "Practice List" and clicking on save button, and again modifying that item I can see that the dropdown list is not holding its selected value i.e., "Practice List". Instead it is holding its default value i.e., "My List". How can I make it hold the selected value after saving the data?
Here's my html code:
<select id="{{::prefix}}_Select_Practice" name="FreeTextDrugSchedule" ng-options="option as option.name for option in data.practiceOptions" class="form-control medium" ng-model="data.saveIn" style="margin-bottom: 5px;">
<option value="" selected="selected">My list</option>
</select>
<button id="{{::prefix}}_Button_Submit" class="btn btn-primary" ng-click="validations = null; doSubmit()">{{submitVerb}}</button>
Here's my js file code:
$scope.doSubmit = function (dataToSubmit) {
$scope.submitted = true;
if (dataToSubmit) {
if ($scope.data.saveIn) {
dataToSubmit.dataToSubmit.saveIn = $scope.data.saveIn;
}
$scope.data = dataToSubmit.dataToSubmit ? dataToSubmit.dataToSubmit : dataToSubmit;
}
validateSubmission();
// TODO simplify this validation
if ($scope.EnterDetailsForm.$invalid || $scope.showEffectiveDateError ||
$scope.showEffectiveDateRangeError || ($scope.sigValidations &&
$scope.sigValidations.length)
|| ($scope.data.pharmacy1 && $scope.data.pharmacy1 == $scope.data.pharmacy2)
|| ($scope.showMDD && (!$scope.data.medication.maximumDailyDose || ($scope.showMDD == 'pd' && !$scope.data.medication.maximumDailyDoseUnit)))
|| $scope.showProviderError
|| $scope.showSupervisorError
|| $scope.drugMinError
|| $scope.showPrimaryError) {
$scope.validations.push({
name: 'Invalid Entry',
msg: 'Please correct all errors on this form to continue.'
});
if ($scope.entity == 'Prescription') {
$scope.scrollToError = true;
}
} else if ($scope.entity == 'Prescription' && !validateDuration()) {
$scope.$emit('ghostMessage', 'The length of the prescription should not be more than 365 days');
} else { //proceed with submission
// prepare the data to be submitted to the alert checker
var dataToSubmit = prepareDataToSubmit();
// validate payload before submit
if (dataToSubmit.medication.lastRefillDate && dataToSubmit.medication.startDate && dataToSubmit.medication.lastRefillDate.date < dataToSubmit.medication.startDate.date) {
$scope.$emit('ghostMessage', 'Last written date cannot be before start date.');
} else if (dataToSubmit.medication.lastRefillDate && dataToSubmit.medication.stopDate && dataToSubmit.medication.lastRefillDate.date > dataToSubmit.medication.stopDate.date) {
$scope.$emit('ghostMessage', 'Last written date cannot be after stop date.');
} else if (dataToSubmit.medication.diagnoses && dataToSubmit.medication.diagnoses.length == 2 && dataToSubmit.medication.diagnoses[0].code &&
dataToSubmit.medication.diagnoses[0].code == dataToSubmit.medication.diagnoses[1].code) {
$scope.$emit('ghostMessage', 'You may not specify the same diagnosis code for both primary and secondary diagnoses');
} else if ($scope.entity != 'FavoriteRx' && $scope.showDAWGenericWarning && !$scope.formularyCheckedForDAWWarning) {
checkFormularyAlertsForDAWWarning(dataToSubmit);
} else {
$scope.formularyCheckedForDAWWarning = false;
// check dose alerts if necessary
dataToSubmit.schedules = angular.copy(schedules);
if ($scope.entity == 'Prescription' && doseCheckNeeded) {
checkDoseAlerts(dataToSubmit);
} else { // done; process submission
$scope.submit({data: dataToSubmit, optionCodes: $scope.optionCodes});
$scope.loading = 0;
}
}
}
};
I'm not exactly sure what you are asking for, or what you mean by "saving" the data, but I will try to offer some assistance.
I don't know angular.js, but my suggestion would be to wrap the select in a form (which I assume you're doing) and then set the value using the post value in angluar.js (if you can do that). That way, if you reload the page, it will not load the default value. Additionally, if you're merely inspecting the element in a browser after you select a new option, it won't show you that a new option is selected (i.e. the selected="" attribute will still be on the default).
Hey guys I am using JavaScript to select a specific value(option) from the html select form tag, but whenever I call my JavaScript function I get a single message repeating for all the choices I want to select.
Ex: If I choose to select 'Rabbit' from the list of options and then display a message saying 'Rabbit chosen'; the message will display for each option/value selected.
Here is my JavaScript Code:
var element = document.getElementById('choices').value;
function SelectElement() {
if (element = 'Rabbit') {
alert("Rabbit Selected");
}
else if (element = 'Wall') {
alert("Wall Selected");
}
else if (element = 'Arrow') {
alert("Arrow Selected");
}
}
Here is my html code:
<form>
<select id="choices" >
<option>Rabbit</option>
<option>Wall</option>
<option>Arrow</option>
</select>
<input type="button" value="Submit" onclick="SelectElement()"/>
</form>
Can you smart guys please help me????
A. You should fetch the value each time before calling the function and then check it otherwise your element variable won't refresh at all.
B. To compare two values you should use ==, = is an assignment operator.
function SelectElement() {
var element = document.getElementById('choices').value;
if (element == 'Rabbit') {
alert("Rabbit Selected");
}
}
(As your question is not much clear) if you just want to alert the selected value for every option clicked, just do:
function SelectElement() {
var element = document.getElementById('choices').value;
alert(element+" Selected");
}
This is basic string concatenation.
There is a something called selected == true or false in a "select" tag.
You could write in HTML :
<form>
<select id="choices">
<option id="Rabbit">Rabbit</option>
<option id="Wall">Wall</option>
<option id="Arrow">Arrow</option>
</select>
</form>
<button onclick="TakeElement()">Click</button>
You could write in javascript:
var ra = document.getElementById('Rabbit');
var wa = document.getElementById('Wall');
var ar = document.getElementById('Arrow');
function TakeElement() {
if (ra.selected == true) {
alert("Rabbit is selected");
}
if (wa.selected == true) {
alert("Wall is selected");
}
if (ar.selected == true) {
alert("Arrow is selected");
}
}
I think you must replace element ='rabbit' with element =='rabbit'
== is comparison operator
and = is assignment operator
I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>
I have one select box and one text box are there. I need to the validation like if both are selected I need alert like "Either select a name or pick the name", If I did not select both i need alert like "Please select a name or pick the name", If I select one of them I need alert like "Thank you for selecting the name". I did it by java script but I did not get the result. Can it be done by using java script / Jquery? Any suggestions
<body>
pick name:
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</br>
select name:
<input type= "text" name="raju" id="raju"></input>
<input type="button" onclick="Validate()" value="select" />
<script type="text/javascript">
function Validate()
{
var name = document.getElementById("raju");
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0 && (name==null || name== ' '))
{
alert("Please select a name or pick the name");
}
else if( (!(strUser==0)) &&(! (name==null || name== ' ')))
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
</script>
</body>
Here is your same validation using JQuery as you also mentioned:
function Validate()
{
var name = $("#raju").val();
var selected_name = $('#ddlView :selected').val();
if(selected_name == 0 && name == "")
{
alert("Please select a name or pick the name");
}
else if( !(selected_name == 0) && name != "")
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
Fiddle
Your problem is that you get the input, not the value.
Replace var name = document.getElementById("raju"); with var name = document.getElementById("raju").value;
Also, you compare the name with null and blank space. You must compare it with empty string. (name == '')
When you saw on my Jsfiddle code, I don't use oonclick attribute but a event listener on javascript (realy better for your html)..
document.getElementById("myBtn").onclick= function ()
One second poitn you have forget tu retrieve .value of you name input (so already return [HTML DOM object] and not null or a value.
var name = document.getElementById("raju").value;
Since your post was in pure JavaScript, I've decided to answer accordingly. As mentioned, you shouldn't check an empty string for " " but rather '' or "". Furthermore, you shouldn't even need to do that, since you can simply check if (str) { // string exists }. For your name variable, you're referring to an HTML element and not it's string value. So, all in all (a few errors), nothing majorly wrong here.
I've abstracted this process a tiny bit to give you an idea of how to validate many similar fields without a whole lot of repetitive code.
Note: You should find a way to replace your inline event handlers with unobtrusive handlers. Example:
document.getElementById('someButton').onclick = Validate;
That being said, here's a few suggestions:
var emptyString = function(str) {
if (str) {
return false;
}
return true;
};
var emptySelect = function(sel) {
if (parseInt(sel) !== 0) {
return false;
}
return true;
};
function Validate() {
var name = document.getElementById("raju").value;
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
switch (true) {
case (!emptySelect(strUser) && !emptyString(name)):
alert('Either select a name or pick a name.');
break;
case (emptySelect(strUser) && emptyString(name)):
alert('Please select a name or pick a name.');
break;
default:
// Possibly some default validation
alert('Thanks for picking a name');
break;
}
}
I have two functions: One the validates the information in name fields of a form, and another that takes the information in those fields and prints them out in an alert box. Separately these functions work fine. I have to call them both, so I created a wrapper function. The function runs, but it refreshes instead of focusing. The weird thing is, if I check the first field, everything is fine, including the .focus();, but when I try to validate the second field, .focus(); doesn't work and the page refreshes. Any help would be appreciated. (I tried to revise my first question to add this, but when I went to save it, nothing happend.)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
function validate() {
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25) {
alert("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25) {
alert("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0) {
alert("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
In your form, you have an erroneous attribute "form" in your <form>, "select" in the middle of the <select> tag, and "input" in the <input> tags. I'm not sure what they are there for, or whether they are causing you trouble, but you should get rid of them nonetheless.
Also, your problem is this line:
document.getElementsByName('lastname').focus();
document.getElementsByName() returns an array, and there is no focus() method on an array. This was causing your issue with validating the last name.
Change it to match your other focus() calls:
document.getElementById('lastname').focus();
I also removed the temporary variable in your main() method:
function main(form) {
if (validate()) {
concatinate();
return true;
}
return false;
}
Working Demo: http://jsfiddle.net/cFsp5/4/
Your main function must return false if validation doesn't pass. Otherwise, it will return undefined, and the form will submit anyway (which is what you describe). So a simple fix would be:
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
return false;
}
http://jsfiddle.net/LhXy4/