Javascript : How to properly check if selected option is empty? - javascript

I have selected option here, I don't know why If I didn't choose any option that means (-select-) values="" no values, still not work. My select option is an array because it on the loop.
Here is my code
var randomGender_arr = [];
var tae = true;
if(randGender == 'random'){
$('select[name="randomGender[]"]').each(function(k,v){
if($(v).val()===''){
alert('Please select a gender')
}else{
randomGender_arr.push($(v).val());
}
});
}else{
}
Btw my selected option is here, as you can see my first option is disabled. How could it be consider as empty? And check if when I leave even 1 of the the option (-select-) then return false.
echo'<div style="float:right; position:absolute; top:10px; right:0;">
<label for="randomGender">Gender:</label>
<select name="randomGender[]" id="randomGender" class="form-control randomGender">
<option disabled readonly selected>-select-</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<div style="clear:both;"></div>';

let changeTime = 0;
let opt = document.querySelector(".opt");
let submit = document.querySelector(".submit");
let notif = document.querySelector(".notif");
opt.addEventListener("change",function(){
changeTime++;
});
submit.addEventListener("click",function(){
if(changeTime != 0){
// Success
notif.textContent = "Success";
}else{
notif.textContent = "Please chose at less one time!";
}
});
<div class="opt" style="float:right; position:absolute; top:10px; right:0;">
<label for="randomGender">Gender:</label>
<select name="randomGender[]" id="randomGender" class="form-control randomGender">
<option disabled readonly selected>-select-</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<div style="clear:both;"></div>
<button class="submit">Button</button>
<p class="notif"></p>

Related

Open Another Input Text when the user selects an option

I am a newbie and I have this project where the user should have the option of custom input if the listed options are not in dropdown.
HTML
<div class="form-group">
<label class="col-sm-2 col-form-label">Select Page Size</label>
<select name = 'pageSelector' class="col-sm-3">
<option value ="">Select Page Size</option>
<option value ="84.1|118.9">A0</option>
<option value = "59.4|84.1">A1</option>
<option value = "7.4|10.5">A7</option>
<option value = "custom">Select Custom</option>
</select>
</div>
PHP
if(isset($_POST["pageSelector"]))
{
$result = $_POST['pageSelector'];
if($result == "")
{
echo "<script>alert('Please select the Page')</script>";
}
$result_explode = explode('|', $result);
$width_page = $result_explode[0];
$height_page = $result_explode[1];
// Converting the string variables to integer
$width_plate=(double)$width_plate;
$height_plate=(double)$height_plate;
$width_page=(double)$width_page;
$height_page=(double)$height_page;
// To calculate the number of pages that can be print with one selected plate
$calculated_width = $width_plate/$width_page;
$calculated_height = $height_plate/$height_page;
$print_include = (int)$calculated_height*(int)$calculated_width;
echo "<div class='h1'>Number of Prints in one plate ".$print_include." prints</div> ";
}
I would like if the user selects the custom option then a input text should appear on the screen.
If user selected a custom option then you can give him an input.
let selectEl = document.getElementById('select-list');
selectEl.addEventListener('change', (e) => {
if (e.target.value == 'custom') {
document.getElementById('txt-custom').style.display = 'block';
} else {
document.getElementById('txt-custom').style.display = 'none';
}
});
#txt-custom {
display: none;
}
<select id="select-list">
<option value="">Select an option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="custom">Custom</option>
</select>
<input type="text" id="txt-custom" name="custom-value" />
var pageSelector = document.getElementById('pageSelector');
var customInput = document.getElementById('customInput');
pageSelector.addEventListener('change', function(){
if(this.value == "custom") {
customInput.classList.remove('hide');
} else {
customInput.classList.add('hide');
}
})
.hide {
width: 0;
height: 0;
opacity: 0;
}
<div class="form-group">
<label class="col-sm-2 col-form-label">Select Page Size</label>
<select name = 'pageSelector' class="col-sm-3 page" id="pageSelector">
<option value ="">Select Page Size</option>
<option value ="84.1|118.9">A0</option>
<option value = "59.4|84.1">A1</option>
<option value = "7.4|10.5">A7</option>
<option value = "custom">Select Custom</option>
</select>
<input type="text" class="hide" placeholder="Custom Selector" name="custom" id="customInput">
</div>
Demo Code :
First you should have input with style="display:none" and with jQuery
jQuery(document).ready(function() {
jQuery("#selectId").change(function() {
if (jQuery(this).val() === 'custom'){
jQuery('input[name=other_input]').show();
} else {
jQuery('input[name=other_input]').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<select name = 'pageSelector' class="col-sm-3" id="selectId" >
<option value ="">Select Page Size</option>
<option value ="84.1|118.9">A0</option>
<option value = "59.4|84.1">A1</option>
<option value = "7.4|10.5">A7</option>
<option value = "custom">Select Custom</option>
</select>
<br><br><br>
<input type="text" name="other_input" style="display:none" />
Angular Version
Angular CLI: 13.0.3
Node: 16.15.0
Package Manager: npm 8.5.5
In .html File
**<div class="col-md-6">
<label class="form-label">Attendence Type</label>
<select (change)="type($event)" class="form-select" aria-label="Default select example" >
<option selected value="P">Present</option>
<option value="A">Absent</option>
<option value="PL">Paid Leave</option>
<option value="UL">Unpaid Leave</option>
</select>
</div>**
I want to Show this input after select paid leave
**<div *ngIf="plFlag" class="col-md-6">
<label class="form-label">Leave Type</label>
<select class="form-select" aria-label="Default select example">
<option selected disabled>Leave Type</option>
<option value="CL">Causel Leave</option>
<option value="SL">Seek Leave</option>
</select>
</div>**
and in .ts File
**type(event: any) {
console.log(event.target.value);
if (event.target.value == "PL") {
this.plFlag = true;
}
else {
this.plFlag = false;
}
}**

How to get a PHP array index converted to a javascript variable

I'm getting a set of user roles from the database using PHP and they are put in a <select> tag's <option>s as follows:
<div class="col-md-3">
<select name="role" id="user_role" class="form-control" onkeyup="clearMsg('roleerr')" onchange="getRole()"/>
<option value="">Select a Role</option>
<?php while($rowrole = $resultrole->fetch(PDO::FETCH_BOTH)) { ?>
<option value="<?php echo $rowrole ['role_id']; ?>">
<?php echo $rowrole ['role_name']; ?>
</option>
<?php } ?>
</select>
<span id="roleerr" class="error">*</span>
</div>
And I want to get the selected value of the dropdown 'onchange' and for that getRole() javascript function is written. How to get this done?
When the element changes, the value of the dropdown will be set to the value attributed to the selected option. So you would just define your javascript function and have it fetch the value of the dropdown:
function getRole(){
var finalVal = document.getElementById("user_role").value;
// And then here you can do whatever you want with the information
}
You can assign value in paramater in onchange()
this should work below
function getRole(value) {
if(value != "")
alert(value)
}
<div class="col-md-3">
<select name="role" id="user_role" class="form-control" onchange="getRole(this.value)"/>
<option value="">Select a Role</option>
<option value="23">select 23</option>
<option value="24">select 24</option>
<option value="25">select 25</option>
</select>
<span id="roleerr" class="error">*</span>
</div>
You could try event of onchange.
onchange="getRole(event)"
Javascript.
function getRole(event) {
var selectElement = event.target;
var value = selectElement.value;
alert(value);
}
I tested it with hard data.
function getRole(event) {
var selectElement = event.target;
var value = selectElement.value;
alert(value);
}
<div class="col-md-3">
<select name="role" id="user_role" class="form-control" onchange="getRole(event)"/>
<option value="">Select a Role</option>
<option value="1">admin</option>
<option value="2">user</option>
<option value="3">support</option>
</select>
<span id="roleerr" class="error">*</span>
</div>

Choosing option from dropdown menu does not show what it should

Maybe someone can tell me how i can repair problem with choosing from Paypal/Bitcoin/Credit Card, coz i tried almost everything, nothing work like it should
I tried also to make them child()/children()/next() and so on nothing help
<select id="payment" name="user-payment">
<option value="select method">Select Payment Method</option>
<option value="Credit Card">Credit Card</option>
<option value="PayPal">PayPal</option>
<option value="Bitcoin">Bitcoin</option>
</select>
$paymentOptionsCard.change(()=>{
// if credit card
if($paymentOptions.val()==='Credit Card'){
$creditCard.show();
bullPay = true;
}
else{
$creditCard.hide();
bullPay = false;
}
});
$paymentOptionsPaypal.change(()=>{
if($paymentOptionsPaypal.val()==="PayPal"){
$paypal.show();
bullPay = true;
}
else{
$paypal.hide();
bullPay = false;
}});
$paymentOptionsBitcoin.change(()=>{
//if bitcoin
if($paymentOptionsBitcoin.val()==="Bitcoin"){
$bitcoin.show();
bullPay = true;
}
else{
$bitcoin.hide();
bullPay = false;
}
});
That's the variables /
//getting payment options
const $paymentOptions = $("#payment");
//selecting default as Credit card
const $paymentOptionsBitcoin = $paymentOptions.val("Bitcoin");
const $paymentOptionsPaypal = $paymentOptions.val("PayPal");
const $paymentOptionsCard = $paymentOptions.val("Credit Card");
I expect that code will "show" or 'hide' values and if that true or false attribute will assign it to the variables.
Now it only show, without assigning all of them
You bind to the select with the change, not its options. You should just bind one change event to the select. This is a easy way of doing it without repeating a lot of code.
// reference the select element
var sel = document.querySelector('#payment')
// add change event
sel.addEventListener('change', () => {
// get the section that is active
var paymentActive = document.querySelector('.payment-section.active')
// if we have one hide it.
if (paymentActive) paymentActive.classList.remove("active")
// reference the option value that was selected
var selection = sel.value
// select the section based on the value
var payment = document.querySelector("#" + selection)
// show the section
if (payment) payment.classList.add("active")
})
.payment-section {
display: none;
}
.payment-section.active {
display: block;
}
<select id="payment" name="user-payment">
<option value="select method">Select Payment Method</option>
<option value="CreditCard">Credit Card</option>
<option value="PayPal">PayPal</option>
<option value="Bitcoin">Bitcoin</option>
</select>
<div id="CreditCard" class="payment-section">Credit Card</div>
<div id="PayPal" class="payment-section">Pay Pal</div>
<div id="Bitcoin" class="payment-section">Bitcoin</div>
I am not very clear of the question but one mistake I can point out is that on the second and third onchange event the "if" condition seems to be wrong
if($paymentOptionsPaypal.val()==="PayPal")
if($paymentOptionsBitcoin.val()==="Bitcoin")
should have been
if($paymentOptions.val()==="PayPal")
if($paymentOptions.val()==="Bitcoin")
$(function() {
$('#payment').change(function(){
$('.colors').hide();
var pm= $(this).val();
$('#' + pm).show();
if(pm=='credit_Card'){
console.log('Credit Card');
}
else if(pm=='payPal'){
console.log('PayPal');
}
else if(pm=='bitcoin'){
console.log('Bitcoin');
}
});
});
#credit_Card,#payPal,#bitcoin {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button dropdown">
<select id="payment">
<option value="">Select Payment Method</option>
<option value="credit_Card">Credit Card</option>
<option value="payPal">PayPal</option>
<option value="bitcoin">Bitcoin</option>
</select>
</div>
<div class="output">
<div id="credit_Card" class="colors red"> Your Payment method is Credit Card</div>
<div id="payPal" class="colors yellow"> Your Payment method is PayPal</div>
<div id="bitcoin" class="colors blue"> Your Payment method is Bitcoin</div>
</div>
<footer>
<small>

How to use if else statements in select form?

In my registration page, I'm gonna use two drop-down select that one of them should be hidden if its Negative and if its positive new drop-down will open to choose ...
In mysql table I've table as diabetes name with enom
enum('negative', 'insulin', 'drug', 'ndm', 'mody', '')
Here's my code:
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
For example: If Diabetes is negative value is negative as default then Diabetes Type is hidden
and
If Diabetes is positive then Diabetes type will be appeared to choose items.
those values like insulin, drug, mdm, mody should be inserted into this:
value="positive"
How can I make it through java script?
I can't add class or div or span. Is it possible just through JavaScript using ??
Thank you so much
Use jquery, it is comparatively easier.
$(document).ready(function(){
$("#diabetestype").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").show();
}else{
$("#diabetestype").hide();
}
});
});
To make this code workable, you need to add value of Positive option also. So instead value="" change it to value="positive".
You can even hide the label also:
$(document).ready(function(){
$("#diabetestype").closest("div").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").closest("div").show();
}else{
$("#diabetestype").closest("div").hide();
}
});
});
<div><label for="diabetes">Diabetes:</label>
<select id="diabet" name="diabet" onchange="checkDiabet();">
<option value="negative">Negative</option>
<option value="positive" id="isDiabet">Positive</option>
</select>
</div>
<div id="type" style="display: hidden;">
<label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
<script>
function checkDiabet() {
var isDiabet = document.getElementById("isDiabet").selected;
if (isDiabet == true) { document.getElementById("type").removeAttribute("style"); }
else { document.getElementById("type").style.display = "none"; }
}
</script>
First, set the first select to fire the function checkDiabet() by the attribute onchange. Then give the option an id, which needs to be checked, so you can access it easily.
Then, set the second select to display: none This could be done in a CSS header or file, or like in this case inline. (div style=""), also add an id to access it easily. (div id="type")
Now comes the function checkDiabete(). It checks if the select is selected (can be true or false (bool)). Is selected => show (div id="type"), if not, hide this div (and all of it's contents)
(if is already hidden, it then overwrites the (style="display: none;") with (style="display: none;))
That's it! :)
Try this:
function SelectDiabetes() {
var d = document.getElementById("diabetes").value;
var dType = document.getElementById("diabetestypebox");
if(d == "negative")
dType.style.display = "none";
else
dType.style.display = "block";
}
SelectDiabetes();
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="SelectDiabetes(this.value);">
<option value="negative">Negative</option>
<option value="positive">Positive</option>
</select>
</div>
<div id="diabetestypebox"><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Call a js function onchange of select id diabetes
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="toggleTypes()">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" style="display:none" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Use the following javascript
function toggleTypes(){
var el=document.getElementById('diabetes');
var medElem=document.getElementById('diabetestype');
if(el.value=='positive') {
medElem.style.display='block';
} else {
medElem.style.display='none';
}
}

Drop down text input option

I want a drop down element where user can select from available options or select enter value option which in turn allows to enter value.
I specifically want that user can enter value only when they select "Enter a value " option.
Here is what I have tried so far.
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
} else {
x.find('.holder').val(x.find('option:selected').text());
}
});
JS fiddle
however it wont work properly if i click the enter value option again.
I think there are many plugins that do what you want but if you want to create your own, it's a basic and simple solution.
You can create a select and a textbox with display:none like this:
<select id="ddlDropDownList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="-1">Enter Value</option>
</select>
<input id="txtTextBox" type="text" />
<style>
#txtTextBox{
display:none;
}
</style>
then try this JQuery:
$("#ddlDropDownList").change(function(){
if($(this).val() == '-1'){
$("#txtTextBox").fadeIn();
}else{
$("#txtTextBox").fadeOut();
}
});
Check JSFiddle Demo
I have forked your JSFiddle to http://jsfiddle.net/pwdst/4ymtmf7b/1/ which I hope does what you wanted to achieve.
HTML-
<div class="ginput_container">
<label for="input_1_4">Select option</label>
<select class="medium gfield_select" id="input_1_4" name="input_4" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<div>
<label class="hidden-label" for="input_1_4_other">Other value</label>
<input class="holder" id="input_1_4_other" disabled="disabled" name="input_1_4_other" placeholder="None" type="text" />
</div>
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var $this = jQuery(this);
var val = $this.val();
var holder = $this.parent().find('.holder');
if (val === "*"){
holder.val('');
holder.removeAttr('disabled');
holder.focus();
} else {
holder.val(this.options[this.selectedIndex].text);
holder.attr('disabled', 'disabled');
}
});
When the "Enter value" option is chosen then the input box is enabled, value set to an empty string, and it is focused. If another option is chosen then the text input is disabled again, and the text value from the select list is used.
Thanks guys
I guess i have found my answer
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
jQuery(this).val("0"); // Change select value to None.
} else {
x.find('.holder').val(x.find('option:selected').text());
x.find('.holder').prop('disabled',true);
}
});
JS FIDDLE

Categories

Resources