How to write this in a simpler less ridiculous way - javascript

This just seems absurd to me. Should I use array instead or is there some other better solution?
$('.hoursRange').change(function() {
if ('0' == $(this).val())
{
$(this).val('00');
return false;
}
if ('1' == $(this).val())
{
$(this).val('01');
return false;
}
if ('2' == $(this).val())
{
$(this).val('02');
return false;
}
if ('3' == $(this).val())
{
$(this).val('03');
return false;
}
if ('4' == $(this).val())
{
$(this).val('04');
return false;
}
if ('5' == $(this).val())
{
$(this).val('05');
return false;
}
if ('6' == $(this).val())
{
$(this).val('06');
return false;
}
if ('7' == $(this).val())
{
$(this).val('07');
return false;
}
});

Just use a regex:
$(this).val($(this).val().replace(/^[0-7]$/, "0$&"));

if($(this).val().length == 1) {
$(this).val('0' + $(this).val());
}
Or just pad all of the single digits with zeros on page load, rather than onchange:
$('.hoursRange option').filter(function() {
return $(this).val().length == 1;
}).each(function() {
$(this).val('0' + $(this).val());
});
Demo: http://jsfiddle.net/WKdWq/

$(this).val('0' + $(this).val());?

var value = $(this).val();
if ($(this).val().length < 2) {
$(this).val('0' + value);
}

$('.hoursRange').change(function() {
if (parseInt($(this).val(),10)<10) $(this).val("0"+parseInt($(this).val(),10));
}

A function for zero-padding is available from this answer. Using that, you can simply do:
$('.hoursRange').change(function() {
$(this).val( zerofill($(this).val(), 2) );
}

$('.hoursRange').change(function() {
$(this).val( $(this).val().replace(/(\b\d\b)/,'0$1') );
}
I don't see you needing any conditional statements or additional expensive jQuery calls in here.

I am not an expert on jQuery but it is awkward.
I would check boundary condition (0<=$(this).val()<=7) and if not met return false. Otherwise
var v = $(this).val();
v='0'+v;
$(this).val(v);

Related

Replace multiple if statements with loop?

Can this code be shortened by looping through the array and replacing the number in input[name="shelf-1"] instead of having multiple if statements?
if(com_array[0] == "ON")
{
$('input[name="shelf-1"]').bootstrapSwitch('state', true);
}else{
$('input[name="shelf-1"]').bootstrapSwitch('state', false);
}
if(com_array[1] == "ON")
{
$('input[name="shelf-2"]').bootstrapSwitch('state', true);
}else{
$('input[name="shelf-2"]').bootstrapSwitch('state', false);
}
if(com_array[3] == "ON")
{
$('input[name="shelf-3"]').bootstrapSwitch('state', true);
}else{
$('input[name="shelf-3"]').bootstrapSwitch('state', false);
}
Assuming that you want to do this for all elements inside the array, you can use a forEach loop as so:
com_array.forEach( (element, index) => {
if(element == "ON") {
$(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', true);
}else{
$(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', false);
}
})
Updated for refactoring option:
If you want it to be cleaner and less repetitive, you can do away with the if-else statement, and use "element == 'ON' as the condition inside bootstrapSwitch:
com_array.forEach( (element, index) => {
$(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', element == "ON");
})
And then you can refactor further to one line
com_array.forEach((element, index) => $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', element == "ON"))
com_array.forEach(function(com, index) {
$('input[name="shelf-' + (index + 1) + '"]').bootstrapSwitch(
'state',
com == 'ON'
)
}
);
I made it IE-11 compatible (i.e. no arrow functions and string template literals). Because I assume you have no transpilation step.
For the non-IE compatible answer (modern js) check the first comment to the question with code.
You could create a function and reuse it:
const bootstrapSwitch = (key, value) = {
$(`input[name="shelf-${key}"]`).bootstrapSwitch('state', value);
}
bootstrapSwitch(0, com_array[1] == "ON")
bootstrapSwitch(1, com_array[2] == "ON")
bootstrapSwitch(3, com_array[3] == "ON")
You can replace the numbers using the index of the array.
let com_array = ['ON','OFF','ON'];
for (index = 0; index < com_array.length; index++) {
if (com_array[index] === 'ON') {
$('input[name="shelf-'+(index+1)+'"]').bootstrapSwitch('state', true);
} else {
$('input[name="shelf-'+(index+1)+'"]').bootstrapSwitch('state', false);
}
}

Jquery: check if variable is defined after keyup() function

Am creating register form with jquery function keyup(),
for example if input is correct I assign it to a txtuname variable,then I press register button and I need to know that all form variables are correct and defined.Code below is not working:
<script type="text/javascript">
$("document").ready(function() {
$("#txtuname").keyup(function() {
if ($("#txtuname").val().length < 6) {
jQuery("label[for='txtuname']").text("user name is too short");
}
if ($("#txtuname").val().length >= 6) {
var txtuname = $("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function() {
if (typeof txtuname == 'defined') {
alert("defined");
}
if (typeof txtuname == 'undefined') {
alert("undefined");
}
});
});
</script>
Modified code. Main point of this code is that txtuname should be visible in both scopes of keyup event listner and click listner. So if there are more lements, create Validation object and just check whether all the values was set and correct. And yes, use or $ or jQuery in your code.
$("document").ready(function(){
var txtuname = null;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if( txtuname == null || txtuname.length < 6) ){
alert("incorrect");
}
else{
alert("correct");
}
});
});
Updated check of variable using comment of #Rhumborl , thx
Replace code with below condition -
if( typeof txtuname !== 'undefined' && txtuname.length >= 6) ){
//proceed further
}else{
alert('Please correct entries.');
return false;
}
I would put the validation logic in a function and call that, you can update this with your specific requirements and only do it once:
function isValidName(field) {
var myName = field.val().trim();
// some of this is redundant but just to show possibilities
var isValid = myName.length && myName.length >= 6 && myName && undefined !== myName && myName != " ";
var myLabel = $("label[for='" + field.attr('id') + "']");
if (isValid) {
myLabel.text("");
} else {
myLabel.text("user name is too short");
}
return isValid;
}
$("document").ready(function() {
$("#txtuname").keyup(function() {
isValidName($(this));
});
$("#submitRegistration").click(function() {
var nameIsValid = isValidName($("#txtuname"));
if (nameIsValid) {
alert("valid");
} else {
alert("undefined or invalid");
}
});
});
You are using $ as well as jQuery window.jQuery object in your code. Do not use both at time , you can check by both
jQuery("document").ready(function() { jQuery("#txtuname").keyup(function(){ if(jQuery("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if(jQuery("#txtuname").val().length>=6){
var txtuname=jQuery("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
jQuery("#submitRegistration").click(function(){
if(typeof txtuname =='defined'){
alert("defined");
}
if(typeof txtuname =='undefined'){
alert("undefined");
}
});
});
Or use by replace jQuery by $ sign. It will work.
you can try this way too......
$("document").ready(function(){
var txtuname;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if(typeof txtuname=="undefined"){
alert("undefined");
}
else{
alert("defined");
}
});
});

jConfirm message cannot work properly

The confirmation popup always return true. Please advice the correction needed.
$('#btnDelete').click(function () {
var check = false;
var aCheckbox = document.getElementsByTagName('input');
for (var i = 0; i < aCheckbox.length; i++) {
if (aCheckbox[i].type === 'checkbox' && aCheckbox[i].checked) {
check = true;
}
}
if (check === true) {
return jConfirm('Do u really want to delete?', 'Confirmation');
} else {
jAlert("Please select serial number", 'Alert');
return false;
}
});
Hope this help :
if (check === true) {
var answer = confirm('Do u really want to delete?', 'Confirmation');
if(answer)
return true;
else
return false;
}
else {
jAlert("Please select serial number", 'Alert');
return false;
}
Yes it creates problem you need to use third parameter as callback function of jconfirm like,
if (check === true) {
jConfirm('Do u really want to delete?', 'Confirmation', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
return false;
} else {
.....
Also remove extra closing }); from your code, see last two lines.

Get default value of an input using jQuery

$(".box_yazi2").each(function () {
var default_value = this.value;
$(this).css('color', '#555'); // this could be in the style sheet instead
$(this).focus(function () {
if (this.value == default_value) {
this.value = '';
$(this).css('color', '#000');
}
});
$(this).blur(function () {
if (this.value == '') {
$(this).css('color', '#555');
this.value = default_value;
}
});
});
This function of default value of input doesnt work in FF, but perfectly works in IE
and ofcourse the input itself looks like this:
<input type="text" class="box_yazi2" id="konu" name="konu" value="Boş" />
Just use the defaultValue property:
var default_value = $(this).prop("defaultValue");
Or:
var default_value = this.defaultValue;
The solution is quite easy; you have an extra }); in your code (thanks # Box9).
I would encourage you to reuse the variable and not create dozens of jQuery objects.
I've changed your example to background-color but it will work.
$('.box_yazi2').each(function(index, element) {
var $element = $(element);
var defaultValue = $element.val();
$element.css('background-color', '#555555');
$element.focus(function() {
var actualValue = $element.val();
if (actualValue == defaultValue) {
$element.val('');
$element.css('background-color', '#3399FF');
}
});
$element.blur(function() {
var actualValue = $element.val();
if (!actualValue) {
$element.val(defaultValue);
$element.css('background-color', '#555555');
}
});
});
demo
$('input[type="text"]').focus( function(){
elementValue = $(this).val();
$(this).val("");
});
$('input[type="text"]').blur( function(){
if($(this).val() != elementValue && $(this).val() != ""){
}else{
$(this).val(elementValue);
}
});
I'm using the next code:
//clear the focused inputs
$('input[type="text"]').focus( function(){
if( $(this).attr('value') == $(this).attr('defaultValue') ){
$(this).attr('value', '');
};
} );
$('input[type="text"]').blur( function(){
if( $(this).attr('value') == '' ){
$(this).attr('value', $(this).attr('defaultValue') );
};
} );
Use this.defaultValue
Sorry for the link to w3notcools, http://www.w3schools.com/jsref/prop_text_defaultvalue.asp
You should use prop instead of so many functions to be honest, use 'delegate' instead of 'on' for late static binding.
$('.box_yazi2').each(function() {
$(this).on('focus', function(){
if($(this).val() == $(this).prop('defaultValue')){
$(this).val('');
$(this).css('color', '#000');
}
});
$(this).on('blur', function(){
if($(this).val() == ''){
$(this).val($(this).prop('defaultValue'));
$(this).css('color', '#000');
}
});
});

Same function for multiple jQuery objects

I want the same functions to run for 2 jQuery objects: $('input[type="text"]') and $('textarea[type=text]'). How can I combine those two in the code below? (currently, only input is included).
$('input[type="text"]').focus(function() {
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
});
$('input[type="text"]').blur(function() {
if ($.trim(this.value == '')){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
Thanks!
Try this:
$('textarea[type="text"], input[type="text"]').focus(...).blur(...);
Similarly you can also use jQuery's add function:
$('textarea[type="text"]').add('input[type="text"]').focus(...).blur(...);
May be easier to put a class on it and filter by that.
You could create a plugin:
jQuery.fn.clearDefValueOnFocus = function() {
return this.focus(function(){
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
}).blur(function(){
if (jQuery.trim(this.value) == ''){
this.value = this.defaultValue || '';
}
});
};
$('input[type="text"]').clearDefValueOnFocus();
$('textarea[type=text]').clearDefValueOnFocus();

Categories