Store default values and use in comparison in click event - javascript

The code is not complete atm but demonstrates what i'm trying to do. In my script i have a jQuery function that is storing the default values from all textareas when the pages is first loaded in an array "defaultValues". When the "click function is executed and the idea is to use the array "defaultValues" in the "CheckTextChange" function and check if anny item dosn't match "currentVal". If currentVal has another value a text change has been made and CheckTextChange will return true. I'm wondering, how can i access "defaultValues[]" inside CheckTextChange and how can i use defaultValues[] in the if-statement to check weather anny item dosn't match currentVal?
HTML:
<h3>Text1...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />
Script:
$('#btnClick').on("click", function () {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
var defaultValues = [];
$(document).ready(function(){
$('.txt').each(function () {
var defValue = $(this).get(0).defaultValue;
defaultValues.push(defValue);
var v = defaultValues[0];
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != previousVal) {
isChanged = true;
}
});
return isChanged;
}

you can save the default values as a data attrib...
$(document).ready(function() {
$(".txt").each(function() {
$(this).attr("data-deftxt", $(this).val());
});
});
$('#btnClick').on("click", function() {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function() {
var currentVal = $(this).val();
if ($(this).val() !== $(this).data("deftxt")) {
isChanged = true;
}
});
return isChanged;
}

Use an associative mapping:
var defaultValues = {};
$(document).ready(function(){
$('.txt').each(function () {
defaultValues[$(this).attr('id')] = $(this).val();
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultValues[$(this).attr('id')]) {
isChanged = true;
}
});
return isChanged;
}
And set an ID to your fields:
<h3>Text1...</h3>
<textarea class="txt" id="field1">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt" id="field2">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt" id="field3">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />

You have to break the loop as follow
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function (index) {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultVaules[index]) {
isChanged = true;
return;
}
});
return isChanged;
}

Related

Range slider filter with pure javascript by adding a function to my array.prototype

I have a table populated with animals and need to filter them by population and i want to use a range slider to filter them without using jQuery, just plain javascript, already have 2 filters using array.prototype. Here is my html code:
<fieldset>
<legend>Search by population</legend>
<input id="populationSlider" class="range-slider__range" type="range" value="100" min="194" max="500000" onchange="updateSliderNumber('populationNumber', this.value);">
<input id="populationNumber" type="number" value="100" min="194" max="500000" onchange="updateSliderNumber('populationSlider', this.value);">
<span class="range-slider__value"></span>
</fieldset>
and here is my sript:
(function(document) {
var AnimalFilter = (function(Arr) {
var _input;
var _select;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _onSelectEvent(e) {
_select = e.target;
var tables = document.getElementsByClassName(_select.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filterSelect);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
function _filterSelect(row) {
var text_select = row.textContent.toLowerCase(), val_select = _select.options[_select.selectedIndex].value.toLowerCase();
row.style.display = text_select.indexOf(val_select) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('table-filter');
var selects = document.getElementsByClassName('select-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
Arr.forEach.call(selects, function(select) {
select.onchange = _onSelectEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
AnimalFilter.init();
}
});
})(document);
// Range-slider
function updateSliderNumber(id, value){
document.getElementById(id).value = value;
}
Ant suggestions?Do i need to call another function, or extend my prototype.array?
Thank you in advance!

Disable button only when text input is 0

I have the following code:
var total = document.getElementById('total--input');
document.getElementById('btn-increment-total').addEventListener('click', function() {
if (total.value > 1) {
console.log('enabled');
document.getElementById('btn-decrement-total').enabled = true;
}
total.value++;
});
document.getElementById('btn-decrement-total').addEventListener('click', function() {
if (total.value == 0) {
console.log('disabled');
document.getElementById('btn-decrement-total').disabled = true;
}
total.value--;
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">
The 'decrement' button seems to work and will disable itself when conditions are met.
But the 'increment' button doesn't seem to re-enable the 'decrement' button. Anyone knows why and how to solve this?
There's no enabled attribute, you should use disable="false" :
document.getElementById('btn-decrement-total').disabled = false;
Instead of:
document.getElementById('btn-decrement-total').enabled = true;
_______________________________________________^^^^^^^
Working sample:
var total = document.getElementById('total--input');
document.getElementById('btn-increment-total').addEventListener('click', function() {
total.value++;
if (total.value > 0) {
console.log('enabled');
document.getElementById('btn-decrement-total').disabled = false;
}
});
document.getElementById('btn-decrement-total').addEventListener('click', function() {
total.value--;
if (total.value == 0) {
console.log('disabled');
document.getElementById('btn-decrement-total').disabled = true;
}
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">
enabled isn't a valid attribute, use disabled = false instead
You need to assign the input in an var/let or const.
try this way:
const total = document.querySelector("#total--input");
I had to add an return statement and change some lines of code but this should work.
const disableBtn = function (id, mode) {
document.getElementById(id).disabled = mode;
};
document.getElementById('btn-increment-total').addEventListener('click', function () {
let total = document.getElementById('total--input');
if (total.value >= 0) {
disableBtn('btn-decrement-total', false);
}
total.value++;
});
document.getElementById('btn-decrement-total').addEventListener('click', function () {
var total = document.getElementById('total--input');
total.value--;
if (total.value <= 0) {
disableBtn('btn-decrement-total', true);
return
}
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">
Try to parse the value from the input element to integer before comparing values...
var n1 = Number(document.getElementById('input_element').value).
Then you can check if it meets the condition

How to convert this code in to jQuery

I have this email validation function in plain JavaScript:
function isEmail() {
var slides = document.getElementsByClassName("email");
for (var i = 0; i < slides.length; i++) {
emailValue = slides.item(i).value;
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var res = regex.test(emailValue);
if (res == false) {
alert("Enter valid email");
return false;
} else {
return true;
}
}
}
I want to convert this in to jQuery in this format:
$(document).ready(function() {
$("#form").submit(function() {
$(".email").each(function() {
});
});
});
Is that what you need??
$(document).ready(function() {
$(".button").click(function() {
$("li.email").each(function() {
emailValue = $(this).text();
console.log(emailValue);
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var res = regex.test(emailValue);
if (res == false) {
alert(emailValue+" email invalid");
} else {
alert(emailValue+" email valid");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="email">email_valid#gmail.com</li>
<li class="email">email_valid2#gmail.com</li>
<li class="email">email_invalid#gmailcom</li>
<li class="email">email_valid3#gmail.com</li>
<li class="">not email</li>
</ul>
<input type="button" class="button" value="validate emails"/>
It seams like the code above it trying to validate multiple emails fields on the page. So I'm going to make some dummy data on my js fiddle for you. I also optimized your code so that the variables are cached outside of the loop. If they were cached inside of the $.each loop, then it would create a new variable each time.
function isEmail() {
var slides = $('.email');
var emailValue = null;
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
var res = null;
console.log(slides);
$(slides).each(function(){
emailValue = $(this).val();
res = regex.test(emailValue);
if (res==false){
alert("Enter valid email");
return false;
}
alert("Success!")
return true;
})
}
Here is the JSFiddle

How will i prevent duplication of value and empty value

How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}

I want to Empty the Value of 2 Input-Type-Text, On Checked (Box)

Guys I Need Help I have the Code what can Empty the Value of Single Input by ID i have 2 Input lets say Start time and End time When i Click on All Day it should be Empty Start Time and End Time When i Check this Button...
Here is my Code....
<Input type="text" id="startime" />
<input type="text" id="endtime" />
<input type="check" id="remove" />
<script type="text/javascript">
var imgInput = document.getElementById('startime'),
remove = document.getElementById('remove'),
val = imgInput.value;
remove.onchange = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
</script>
Help Appreciated...
For a checkbox, you should not use the onchange event handler, onclick will do what you need:
remove.onclick = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
However it looks like you might be trying to save the value if it gets cleared so it can be repopulated, if this is the case then you also need to update val before you clear the text box:
remove.onclick = function() {
if (this.checked) {
val = imgInput.value;
imgInput.value = "";
} else {
imgInput.value = val;
}
}

Categories