I'm trying to validate my form using jquery before submission. The user needs to fill up the Task accordingly, they cannot submit the form with fill-up Task 2 and missing Task 1. And also the Task cannot be duplicated with other Task. I'm wondering if there any better way to compare all of this, in a simple method.
The Javascript currently I'm doing. Still not complete yet because looking for better ways.
$(function() {
$( "#create_model" ).submit(function( event ) {
if(validate_task()){
alert("Check your task.");
event.preventDefault();
} else {
$("#create_model").submit();
}
});
});
function validate_task() {
if ($('#CatTask2ID').val() !== "" && $('#CatTask2ID').val() === "") {
return "Task 1 is empty"; //return FALSE;
} else if ($('#CatTask3ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "") {
return "Task 1 or 2 is empty"; //return FALSE;
} else if ($('#CatTask4ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask1ID').val() === $('#CatTask2ID').val() || $('#CatTask1ID').val() === $('#CatTask3ID').val() .......and others........... ) {
return "Duplicates"; //return FALSE;
}
}
First use classes instead of IDs so you can get a collection of all selects easily, then map each select to its value to get an array of values.
Find the index of the first value which is the empty string. If any values after that one are populated, return an error saying that the index of that empty string is empty.
Otherwise, take the populated values (from indices 0 to the index of the first empty string), and check if the size of a Set of those values is equal to the length of the array:
function validate_task() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex > 0 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
// OK
}
Live demo:
document.addEventListener('change', () => console.log(validateTask()));
function validateTask() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex !== -1 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
return 'OK'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
function validate_task() {
var error_msg = [];
if($('#CatTask1ID').val() === ""){
error_msg.push('1');
}
if($('#CatTask2ID').val() === ""){
error_msg.push('2');
}
if($('#CatTask3ID').val() === ""){
error_msg.push('3');
}
//......
return error_msg;
}
function validate_task_msg() {
var arr = validate_task()
if(arr&& arr.length<=0){
return true;
}else if(arr.length == 10){//more
return "Duplicates";
}else {
var msg = arr.join(',');
return "Task "+ msg + " is empty"
}
}
Related
I am trying to show items of game and I want to filter my output results.
I have panel with multiple filters
And I don't know how to do it correct. Some filters are similar, maybe it should move to function.
I tried to do like this (for search by name and one filter), but I am not sure is it the best way or no?
filteredItems() {
if (this.activeFilter && this.activeFilter != "all") {
return this.items[this.activeFilter]
.filter(
item =>
item.name.toLowerCase().indexOf(this.search.toLowerCase()) !== -1
)
.filter(item => {
if (this.minLvl !== "" && this.maxLvl !== "") {
if (
item.itemLevel >= this.minLvl &&
item.itemLevel <= this.maxLvl
)
return true;
} else if (this.minLvl == "" && this.maxLvl !== "") {
if (item.itemLevel <= this.maxLvl) return true;
} else if (this.minLvl !== "" && this.maxLvl == "") {
if (item.itemLevel >= this.minLvl) return true;
} else {
return true;
}
});
}
I'm stumped. I'm trying to check to see if my input type:text is empty, or null, in my JavaScript. I currently have this:
if ($("#startDate").val().trim().length() === 0)
{
alert("Please fill out the required fields.");
}
I have tried: .val() === "", .val() == "", .length() === 0, .length() == 0, .length() < 1, .val().length() === 0, val().trim().length() < 1, .trim().length() < 1, .text() === "", .text() == "", !$("#startDate").val()
My HTML is:
<fieldset>
<label for="startDate_[pk]" style="display:block; width:100%;text-align:left">Start Time</label>
<input type="text" name="startDate_[pk]" id="startDate_[pk]" style="width:75px;display:inline" placeholder="pick date" />
##
<select name="startTime_[pk]" id="startTime_[pk]" style="display:inline;" disabled="disabled">
#{
var time = DateTime.Now.Date.AddHours(8);
for (int i = 480; i < 1260; i += 15)
{
<option value="#i">#DateTime.Now.Date.AddMinutes(i).ToShortTimeString()</option>
}
}
</select>
</fieldset>
I have also tried this:
$('input[class^="dateValidate"]').each(function () {
if($(this).val().trim().length === 0)
{
alert("Please fill out the required fields.");
}
I'm running out of ideas.
****Update****
The validation works for one selected object. But when you select more than one, the validation only works for the first object. Here's my code:
function validate()
{
var startDate = $('[id^="startDate"]').filter(function(){
return $(this).val().length!==0;
});
var showingType = $('[id^="tShowingType"]').filter(function () {
return $(this).val() === "";
});
var startTime = $('[id^="startTime"]').filter(function () {
return $(this).val() === "";
});
var endTime = $('[id^="endTime"]').filter(function () {
return $(this).val() === "";
});
if (startDate.length == 0 || showingType.val() === "" || startTime.val() === "" || endTime.val() === "")
{
alert("Please fill out the required fields.");
}
else
{
UI.goToConfirmStep();
}
I have tried:
var startDate = $('[id^="startDate"]').filter(function(){
return $(this).val().length!==0
var startDate = $('[id^="startDate"]').filter(function(){
return $(this).val().length===0
startDate.length == 0
startDate.length < 0
startDate.length < 1
It seems that you have wrong id mapped- startDate in the selector. In your code you have IDs like startDate_[pk]. So you need a starts with selector like below.
var emptyInputs= $('[id^="startDate"]').filter(function(){
return $(this).val().length===0;
});
if(emptyInputs.length>0){
alert("Please fill out the required fields.");
}
Fiddle Demo
You are not targetting the id correctly
if(!$("#startTime_[pk]").val())
if (!$('#startTime_[pk]').val()) {
console.log('input empty');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input id="startTime_[pk]" type="text" value="" />
Update
the [pk] actually changes because it's a guid that gets loaded up on the page load
Then use the starts with selector
if(!$('[id^="startTime"]').val())
length is not a function. Here is an example of the above code working by removing the parenthesis after length
function validate() {
if ($("#tShowingType").val() === "" || ($("#startDate").val().trim().length === 0) || ($("#startTime").val() === "") || ($("#endTime").val() === "")) {
alert("Please fill out the required fields."); } else { UI.goToConfirmStep();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type='text' id='startDate' />
<button onclick='validate();' >Button</button>
Change the condition to the following:
if(!$('[id^="startDate"]').val()){
alert("Please fill out the required fields.");
}
<select data-placeholder="Please select a payment method.." style="width:50%;" class="chosen" onchange="currencyChange(this.value)">
<option value=""></option>
<optgroup label="Cash">
<option value="Paypal">Paypal</option>
<option value="Bitcoin">Bitcoin</option>
<option value="Western Union">Western Union</option>
<option value="Delivery">Delivery</option>
</optgroup>
<optgroup label="Ingame Currency">
<option value="RS3 GP">RS3 GP</option>
<option value="OSRS GP">OSRS GP</option>
</optgroup>
</select>
<script type="text/javascript">
var sign = "null";
var placement = "null";
float budget = "null";
function currencyChange(data){
if (data === 'Paypal') {
sign = "$";
placement = "before";
}
if (data === 'Bitcoin') {
sign = "$";
placement = "before";
}
if (data === 'Western Union') {
sign = "$";
placement = "before";
}
if (data === 'Delivery') {
sign = "$";
placement = "before";
}
if (data === 'RS3 GP') {
sign = "M/GP";
placement = "after";
}
if (data === 'OSRS GP') {
sign = "M/GP";
placement = "after";
}
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
}
</script>
I am trying to change the currency type of another textfield id="budget" to add a currency symbol dependent on the choice of payment method..?
But I get no such action when selecting the payment type.
remove this, Its works
float budget = "null";
And,
add below select
<input type="text" id="budget">
Edited
if (placement === 'before') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = sign + toreplace.replace("$","");
}
if (placement === 'after') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = toreplace+ sign;
}
Try this fiddle it will not accepting double sign.
http://jsfiddle.net/pee7d6qr/1/
if (placement === 'before') {
if(document.getElementById("budget").value.indexOf("$") == -1){
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
if (placement === 'after') {
if(document.getElementById("budget").value.indexOf("M/GP") == -1){
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
Remove the float variable in javascript
Budget Input element is missing
<input type="text" name="budget" id="budget" value=>
Use the below code
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value.replace(/[^0-9.]/g,'');
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value.replace(/[^0-9.]/g,'') + sign;
}
Now you need to strip those "$,M/GP" stuff from the string
With little help from stackoverflow:
value = document.getElementById("budget").value;
value = value.replace(/\D/g,''); //strip non-numeric characters from string
Then
if (placement === 'before') {
document.getElementById("budget").value = sign +" "+ value;
}
if (placement === 'after') {
document.getElementById("budget").value = value +" "+ sign;
}
jsFiddle
I'm having a problem in disabling textbox and combo box by using another combo box here is my javascript so far:
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val == "Military","Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val == "Dependent","Civilian") ? true : false;
};
and here's my html:
<select name="category" size="1" id="category">
<option selected="selected">Choose...</option>
<option value="Civilian">Civilian</option>
<option value="Military">Military</option>
<option value="Dependent">Dependent</option>
</select>
<select name="bos" id="bos" >
<option value="">Branch of Service</option>
<option value="PAF">PAF</option>
<option value="PA">PA</option>
<option value="PN">PN</option>
<option value="TAS">TAS</option>
</select>
<input id = "afpsn" name="afpsn" type="text" id="afpsn" size="38" placeholder="AFPSN" />
it should be whenever I select dependent or civilian the other combo box and text field will be disabled and will be enable when I select military. please help!
This fiddle will be help you. you can edit logic , too.
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
// alert(val);
document.getElementById("bos").disabled = (val === "Military") ? false : true;
document.getElementById("afpsn").disabled = (val === "Military") ? false : true;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian" ) ? true : false;
document.getElementById("bos").disabled = (val === "Dependent" || val === "Civilian" ) ? true : false;
};
I dont think there is anything like (val == "Military","Civilian")
You can try this Fiddle
Try below code:
/*Function to check if value is in an array*/
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
/*******************************************/
var s=document.getElementById("elementId");
s.disabled = isInArray(s.value,["Military","Civilian"]); //Function automatically returns "true" or "false" depending on value
Demo Fiddle
Try this instead:
Your condition (comparison with strings) is incorrect.
example
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
};
EDIT:
To attach the event on page load (assuming you are not using jQuery), one way is to attach it on pageload like:
function init() {
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
};
}
and something like this on your <body>
<body onload="init();">
...
</body>
The reason why the example worked is that jsfiddle.net loads the functions in the js box on load by default. But in your case, you have to do that manually.
HTML:
<div class="question>
<select name="status">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div class="subquestion">
<input type="file name="file>
</div>
</div>
JS
$(document).ready(function () {
$(".question").each(function () {
$(".subquestion").hide();
$('select[name=status]').click(function () {
if (this.value == "1" || this.value == "2" || this.value == "3") {
// show $(this) div 'subquestion'
}
else {
$(".subquestion").hide();
}
})
})
});
I want to get select values with this select values and then if values are 1 || 2 || 3 then use this div subquestion show();
but it must be outside of if statement beacause there is selected ('select') tag and div subquestion is outside that tag.
If you need to show the subquestion related to that question use this:
$(document).ready(function () {
$(".question").each(function () {
$(".subquestion").hide();
$('select[name=status]').change(function () {
if (this.value == "1" || this.value == "2" || this.value == "3") {
$(this).next('.subquestion').show();
}
else {
$(this).next('.subquestion').hide();
}
})
})
});
Check this Demo http://jsfiddle.net/6ZxDJ/
change this:
$('select[name=status]').click(function () {
if (this.value == "1" || this.value == "2" || this.value == "3") {
// show $(this) div 'subquestion'
}
else {
$(".subquestion").hide();
}
})
to this
$('select[name="status"]').change(function () {
if ($(this).val() == "1" || $(this).val() == "2" || $(this).val() == "3") {
$(this).closest('.question').find(".subquestion").show();
}
else {
$(this).closest('.question').find(".subquestion").hide();
}
})