Preventing code replication in javascript by combining these functions - javascript

So I have two jquery functions that bassically do the same, but on 2 seperate containers. Is there a way to combine these two functions.
$('#autobid-list .auction-button').click(
function(){
if($(this).attr('summary') == 'autobid-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == 'watchlist-button'){
if($(this).hasClass('watchlist-1')){
$(this).parents('li').clone().appendTo('#watchlist-list');
}else{
$('#watchlist-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
);
$('#watchlist-list .auction-button').click(
function(){
if($(this).attr('summary') == 'watchlist-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == 'autobid-button'){
if($(this).hasClass('autobid-1')){
$(this).parents('li').clone().appendTo('#autobid-list');
}else{
$('#autobid-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
);
These two do bassically the same, the only change is the input of either 'autobid' or 'watchlist'

Obvious answer:
$('#watchlist-list .auction-button').click(function(){
whatever.call(this,'watchlist', 'autobid');
});
$('#autobid-list .auction-button').click(function(){
whatever.call(this,'autobid', 'watchlist');
});
function whatever(one, two){
if($(this).attr('summary') == one + '-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == two + '-button'){
if($(this).hasClass(two + '-1')){
$(this).parents('li').clone().appendTo('#' + two + '-list');
}else{
$('#' + two + '-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
Though some rethinking is probably better.
EDIT: Oops, fixed.

Sure, just determine which one was clicked and assign a variable according to that. You can select several elements at once when you separate them with commas:
$('#watchlist-list .auction-button, #autobid-list .auction-button').click(function() {
// Determine which button was clicked, you might want to adjust this as needed.
var type = $(this).closest('#autobid-list').length > 0 ? 'autobid' : 'watchlist';
// Then just replace 'autobid' and 'watchlist' with 'type'
if($(this).attr('summary') == type+'-button') {
$(this).parents('li').addClass('none');
} else if($(this).attr('summary') == type+'-button') {
if($(this).hasClass(type+'-1')) {
$(this).parents('li')
.clone()
.appendTo('#'+type+'-list');
} else {
$('#'+type+'-list .auction-' + $(this).parents('table').attr('summary'))
.parents('li')
.addClass('none');
}
}
});

Could this work? Make a function that returns a function:
function MyFunction(type) {
return function(){
if($(this).attr('summary') == type + '-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == type + '-button'){
if($(this).hasClass(type + '-1')){
$(this).parents('li').clone().appendTo('#' + type + '-list');
}else{
$('#' + type + '-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
}
$('#autobid-list .auction-button').click(MyFunction('autobid'));
$('#watchlist-list .auction-button').click(MyFunction('watchlist'));

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);
}
}

prevent function from recalling itself at the last statement of the function in java script

I've been learning javascript and jquery and I've encountered a problem when I'm trying to validate my form fields using a jquery function. The problem is its working fine the first two times it is called (when I press the update button for a specific element )and whenever I'm trying to call it a third time (by pressing the update button for the same element as earlier ) it is calling itself but I clearly did not mention any recursive calls and am not calling it within the function again. I'm not sure why it is calling itself. Kindly help me out. I will be attaching the fiddle. After triggering reset in main.updateData(Object.assign({}, main.newObject), keys); in the third time its showing the name empty error which shouldn't be happening.
I've tried giving breakpoints and inspecting the reason behind this weird behaviour but I couldn't
The name field should show an error only when it is empty but third time it is showing error even when it is not empty
FIDDLE
validateFormData: function(value, keys, idCount) {
var keyIndex = 0;
main.newObject[keys[keyIndex++]] = idCount;
if (value == "update") {
main.newObject[keys[0]] = $(".active-contact").attr('id');
//alert("new updated id is " + main.newObject[keys[0]]);
}
var validElementsCount = 0;
var alphabet_pattern = /^[a-z]+\s*/i;
var email_pattern = /[a-z]{0,}[0-9]{0,4}[.]{0,1}[0-9]{0,4}[a-z]{0,8}[0-9]{0,4}[#][a-z]{0,20}[.](com)/i;
var number_pattern = /^[0-9]{10}$/;
var website_pattern = /^(www)[.][a-z]{1,20}[.](com)$/i;
/*Validating the form inputs against the regex pattern*/
if ($("#employee-name").val() == "") {
$("#employee-name-error").text("name cannot be empty");
} else if (!alphabet_pattern.test($("#employee-name").val())) {
$("#employee-name-error").text("Only alphabets are allowed");
} else {
validElementsCount++;
$("#employee-name-error").text("");
main.newObject[keys[keyIndex++]] = $("#employee-name").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex-1]]) + " key is " + keys[keyIndex-1]);
}
//employee email validation
if (email_pattern.test($("#employee-email").val()) || $("#employee-email").val() == "") {
$("#employee-email-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-email").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-email-error").text("Follow email pattern");
}
//employee mobile validation
if (number_pattern.test($("#employee-mobile").val()) || $("#employee-mobile").val() == "") {
$("#employee-mobile-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-mobile").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-mobile-error").text("Only 10 digit number is allowed");
}
//employee landline no validataion
if (number_pattern.test($("#employee-land-line").val()) || $("#employee-land-line").val() == "") {
$("#employee-land-line-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-land-line").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-land-line-error").text("Only 10 digit number is allowed");
}
//employee website validation
if (website_pattern.test($("#employee-website").val()) || $("#employee-website").val() == "") {
$("#employee-website-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-website").val();
} else {
$("#employee-website-error").text("Follow website pattern");
}
main.newObject[keys[keyIndex++]] = $("#employee-address").val();
if (validElementsCount == 5) {
if (value == "add") {
main.addEmployeeClick(Object.assign({}, main.newObject));
$(".employee-details-form").trigger("reset");
} else if (value == "update") {
//alert("new object is " + JSON.stringify(Object.assign({}, main.newObject), keys));
main.updateData(Object.assign({}, main.newObject), keys);
$(".employee-details-form").trigger("reset");
}
}
},
You can add .off() before #update-employee-btn click event binding in line 34.
$("#update-employee-btn").off().click(....)
Let me know if it works for you as well.

Trimming in Jquery [duplicate]

This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 8 years ago.
function ShowEditBox(serial)
{
$("#divEditBox").slideDown("medium");
var pserial ='PName'+ serial;
var colindex = 0;
var $tr = $("#" + pserial).parent().parent();
$tr.find('td').each(function () {
if (colindex == 2) {
$("#txtName").val($(this).text());
} else if (colindex == 3) {
$("#txtSurName").val($(this).text());
} else if (colindex == 4) {
$("#txtEmail").val($(this).text());
} else if (colindex == 5) {
$("#txtMobile").val($(this).text());
} else if (colindex == 6) {
$("#txtAddress").val($(this).text());
}
colindex++;
})
$("#hdField").val(serial);
}
Whenever i click the edit button in grid view that particular row data should be displayed in text boxes. But here i am getting unnecessary spaces in text boxes.
How can i trim the spaces in the Text box(txtName) ?? I am getting spaces in text .
Try to use $.trim("string"),
$("#txtName").val($.trim($(this).text()));
use trim() function of javascript
for jquery look at here Trim
Look at here
example
var str = " lots of spaces before and after ";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" );
Use javascript trim() method.
$("#txtName").val($(this).text().trim());
function ShowEditBox(serial)
{
$("#divEditBox").slideDown("medium");
var pserial ='PName'+ serial;
var colindex = 0;
var $tr = $("#" + pserial).parent().parent();
$tr.find('td').each(function () {
if (colindex == 2) {
$("#txtName").val($.trim($(this).text()));
} else if (colindex == 3) {
$("#txtSurName").val($.trim($(this).text()));
} else if (colindex == 4) {
$("#txtEmail").val($.trim($(this).text()));
} else if (colindex == 5) {
$("#txtMobile").val($.trim($(this).text()));
} else if (colindex == 6) {
$("#txtAddress").val($.trim($(this).text()));
}
colindex++;
})
$("#hdField").val(serial);
}

How to write this in a simpler less ridiculous way

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);

how to call another function in javascript?

how do i call the doSubmit() function from the conFirmUpload() when the confirm msg box is true?
<script type="text/javascript">
function confirmUpload() {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
return true;
}
else
return false;
}
function doSubmit(btnUpload) {
if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) {
return false;
}
btnUpload.disabled = 'disabled';
btnUpload.value = 'Processing. This may take several minutes...';
<%= ClientScript.GetPostBackEventReference(btnUpload, string.Empty) %>;
}
</script>
var btnUpload = document.getElementById('buttonId');
doSubmit(btnUpload);
Put that in your if-block. Make sure the button has an ID.
Without knowing more What about this?
function confirmUpload(btnUpload) {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
doSubmit(btnUpload);
}
else
return false;
}
function confirmUpload() {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
var btnUpload = document.getElementById('<%= btnUpload.ClientID %>');
doSubmit(btnUpload);
}
}
Change the method prototype as
function confirmUpload(obj) {
//Do some thing
}
Where obj the the button you are clicking on
Call this method as
**onclick="javaScript:confirmUpload(this)"**
Now in that if part call another method like
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value
+ "' ?") == true) {
doSubmit(obj);
}

Categories