I have this input type="number"
</div>
<input id="data-filter" class="form-control form-control" type="number" value="2021"/>
</div>
What i need is a script that change the input value using the stepUp and stepDown buttons from "2021" to "2022" and then "2021" again. This because i have a function related to that input and the function doesn't read the default value of element input. It happens only if i fill the input text with "2021" again, or i use the stepUp/stepDown buttons.
Edit:
I use that input to perform a search in a table-rows, what i need on the page load is to filter only the rows that contains the year 2021. The function works great, but it doesn't on page load using a default value. So i need to change manualty the input value.
the filter:
$('#data-filter').on('load', function () {
changeFilter.call(this, 'data');
});
the function changeFilter:
function changeFilter(filterName) {
filters[filterName] = this.value;
updateFilters();
}
update filters function:
function updateFilters() {
$('.task-list-row').hide().filter(function () {
var
dataValue = $(this),
result = true;
Object.keys(filters).forEach(function (filter) {
if (filters[filter] && (filters[filter] != 'Tutti') && !filters[filter].includes('-')) {
result = result && dataValue.data(filter).toLowerCase().includes(filters[filter].toLowerCase())
}
else if (filters[filter] && (filters[filter] != 'Tutti') && filters[filter].includes('-')) {
result = result && convertDate(filters[filter]) === dataValue.data(filter);
}
if (filters[filter] === '') {
result = true;
}
});
return result;
}).show();
}
function setUp() {
let dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = ++dataValue;
}
function setDown() {
let dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = --dataValue;
}
function setUp()
{
dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = ++dataValue;
}
function setDown()
{
dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = --dataValue;
}
Related
Trying to get the value (AUD) and using it in the if statement below.
<span class="name" data-name="">AUD</span>
<script>
function myFunction() {
var currency = document.getElementsByClassName("name")[0]
if (currency = AUD) {
In order to compare the currency value to "AUD" in the conditional, you want to do if (currency == "AUD") (this is called a loose comparison) or if (currency === "AUD") (this is called a strict comparison).
Though you need to first get the .innerText of currency. Right now, currency is the first node that was found by getElementsByClassName. So change this to var currency = document.getElementsByClassName("name")[0].innerText to get the text value of the node, and then you can do the conditional like above.
function myFunction() {
//check the first 'name' text
var currency = document.getElementsByClassName("name")[0].innerText;
if (currency == "AUD") {
console.log('currency is AUD');
} else {
console.log('currency is not AUD');
}
//check the second 'name' text
var currency2 = document.getElementsByClassName("name")[1].innerText;
if (currency2 == "AUD") {
console.log('currency is AUD');
} else {
console.log('currency is not AUD, it is ' + currency2);
}
}
myFunction();
<span class="name" data-name="">AUD</span>
<span class="name" data-name="">USD</span>
You could try doing a for loop like this
var currency = document.getElementsByClassName("name");
for(var i = 0; i < currency.length; i++) {
if(currency[i].innerHTML == "AUD") {
}
}
Try this:
function myFunction() {
var currency = document.getElementsByClassName("name")[0].innerHTML;
if (currency == 'AUD'){
console.log(true)
}
}
myFunction();
Try this.
And don't forget to call myFunction() to make it work.
<span class="name" data-name="">AUD</span>
<script>
function myFunction() {
let currency = document.getElementsByClassName('name')[0];
let value = currency.innerText;
let AUD = 'AUD';
if (value == AUD) {
console.log('yes')
}
}
myFunction();
</script>
I want to get the answers to a form upon submission and parse them to JSON.
This works quite good but I want some validation before sending the data.
I tried a lot of variations of the snippet down below but am still stuck.
Steps:
Prevent default event on "send"
Get Form
Iterate through the elements of the form
Eliminate empty items and their value
If checkbox is checked: value = true
Store correct items in data
Return data
Somehow I can't get to work steps 4 and 5 work at the same time, every time I get one of them to work I screw over the other one.
In this snippet, the checkbox works as intented but the textfield doesn't:
If anybody can point me in the right direction with the if/else statements or something like that it would be greatly appreciated.
document.addEventListener('DOMContentLoaded', function(){
var data = {};
var formToJSON = function formToJSON(form) {
var data = {};
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value =="") {
continue;
}
else {
if (item.checked == false) {
data[item.name] = false;
}
else {
data[item.name] = item.value;
}
}
}
return data; };
var dataContainer = document.getElementsByClassName('results__display')[0];
form = document.getElementById('formular').querySelectorAll('input,select,textarea');
butt = document.getElementById('knopfabsenden');
butt.addEventListener('click', function (event) {
event.preventDefault();
handleFormSubmit(form = form);
});
var handleFormSubmit = function handleFormSubmit(event) {
var data = formToJSON(form);
dataContainer.textContent = JSON.stringify(data, null, " ");
}
}, false);
<div id="formular">
<label class="formular__label" for="machineName">Textfield Test</label>
<input class="formular__input formular__input--text" id="machineNumber" name="machineNumber" type="text"/>
<br>
<input class="formular__input formular__input--checkbox" id="checkTest" name="checkTest" type="checkbox" value="true"/>
<label class="formular__label formular__label--checkbox" for="checkTest">Checkbox Test</label>
<br>
<button class="formular__button" id="knopfabsenden" type="submit">Submit</button>
</div>
<div class="results">
<h2 class="results__heading">Form Data</h2>
<pre class="results__display-wrapper"><code class="results__display"></code></pre>
</div>
The problem is .checked will always be false if it doesn't exist. So the text field gets the value false.
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value ==="") {
continue;
}
else {
if (item.type === "text") {
data[item.name] = item.value;
}
else if (item.type === "checkbox"){
data[item.name] = item.checked;
}
}
}
In this code snippet I check the type of the input and handle it accordingly. also notice I use the === operator and not the == operator as a best practice (Difference between == and === in JavaScript)
i have a default array that have some fixed values from which i am showing a multiselect dropdown to user.So on focusout of the drop down i want to check that whether the values are selected have the all those values that are in the default array.If the values are missing i want to alert them to the user
HTML
<form action="#" method="post">
<fieldset>
<label for="selectedItemLists">Select values:</label>
<select id="selectedItemLists" name="selectedItemLists" multiple>
<option val="value1" selected >value1</option>
<option val="value2">value2</option>
<option val="value3" selected>value3</option>
<option val="value4">value4</option>
<option val="value5">value5</option>
</select>
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
jQuery
var default_values = ["value1","value3"];
$("#selectedItemLists").live('focusout',function(){
var new_selectedvalues = $("#selectedItemLists").val();
//here i want to compare both the arrays and alert him that default values are missing
});
A simple nested $.each loop will do it:
Demo
//here i want to compare both the arrays and alert him that default values are missing
$.each(default_values, function(_, defaultVal){
var found = false;
$.each(new_selectedvalues, function(){
if(this == defaultVal){
found = true;
return false;
}
});
if(!found){
alert("Please select the default: " + defaultVal);
}
});
Note: .live() is deprecated from jQuery 1.7, so .on should be used instead (unless you are working with the old version).
Just try with:
var default_values = ["value1","value3"];
$("#selectedItemLists").on('blur',function(){
var values = $(this).val();
if ($(values).not(default_values).length == 0 && $(default_values).not(values).length == 0) {
console.log('equal');
} else {
console.log('not equal');
}
});
http://jsfiddle.net/f5BbT/
try something like this
var default_values = ["value1","value3"];
$("#selectedItemLists").focusout(function() {
var selected_val = $('#selectedItemLists').val();
if(selected_val.length < default_values.length){
alert('value not present');
}else{
var flag = true;
for(var i= 0;i<default_values.length;i++){
if(selected_val.indexOf(default_values[i]) == -1){
flag = false;
}
}
if(!flag){
alert('value not present');
}else{
alert('value present');
}
}
});
I would do someting like this:
var default_values = ["value1","value3"];
var displayValues = [];
$("#selectedItemLists").on('blur',function(){
$.each(default_values, function(index, value) {
if($.inArray(value, $("#selectedItemLists").val()) === -1)
{
displayValues.push(value);
}
});
});
alert(displayValues);
please use
$("#selectedItemLists").on('blur',function(){
instead of
$("#selectedItemLists").live('focusout',function(){
live is deprecated since jQuery 1.7 and removed in 1.9
try this JSFIDDLE
var default_values = ["value1", "value3"];
$("#selectedItemLists").on('blur', function () {
var missing_values = [];;
var values = $(this).val();
//******************************************
//checking missing values in default_values
//******************************************
$.each(values, function (key, value) {
if ($.inArray(value, default_values) == -1) {
missing_values.push(value);
}
});
alert(missing_values);
// alerts missing selected values in default_values
});
or try
var default_values = ["value1", "value3"];
$("#selectedItemLists").on('blur', function () {
var missing_values = [];
var values = $(this).val();
//******************************************
//checking default values in selection
//******************************************
$.each(default_values, function (key, value) {
if ($.inArray(value, values) == -1) {
missing_values.push(value);
}
});
alert(missing_values);
// alerts missing default values in selected
});
I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}
It's possible to override value property in tag? My code in JavaScript
var element = document.createElement('input');
element.type = 'FILE';
element.__defineGetter__('value',function(){ return 'ololo'; });
alert(element.value);
It show empty string. Also I try override 'value' with prototype
function BPFILEINPUT(value)
{
this.value = value;
}
BPFILEINPUT.prototype = element;
var myFileInput = new BPFILEINPUT('ololo');
alert(myFileInput.value);
It work, but crash on
form.appendChild(myFileInput);
I try pass test for upload form on 4shared.com
var uplElems = aUploadForm.elements;
for (var i = 0; i < uplElems.length; i++) {
var currentUploadElement = uplElems[i]
if (currentUploadElement.type == 'file') {
if (currentUploadElement.value == '') {
// skip
} else {
if (!checkFileLength(currentUploadElement)) {
return false;
}
filesToUpload += getNumberOfSelectedFiles(currentUploadElement);
}
}
}
if (filesToUpload < 1) {
alert('You didn\'t select any file to upload yet.');
return false;
}
UPDATE
I use UIWebView.
AFAIK, you can't set the value of <input type="file"> programmatically because of security reasons. A user has to explicitly click on it to set its value.