Condense IF Statement As Seems Over Kill - javascript

New To JQuery, i have the following code which i think is a bit over kill as all i'm trying to do i match a returned value to a selection of buttons and add/remove a class.
HTML for days of the week buttons
<div class="form-horizontal" id="selectWeekdaysSection">
<div class="form-group">
<div class="col-md-offset-2 col-lg-4">
<button id="mon" name="weekdaysbutton" class="btn btn-default" type="button" value="Mon">Mon</button>
<button id="tue" name="weekdaysbutton" class="btn btn-default" type="button" value="Tue">Tue</button>
<button id="wed" name="weekdaysbutton" class="btn btn-default" type="button" value="Wed">Wed</button>
<button id="thur" name="weekdaysbutton" class="btn btn-default" type="button" value="Thur">Thur</button>
<button id="fri" name="weekdaysbutton" class="btn btn-default" type="button" value="Fri">Fri</button>
<button id="sat" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sat">Sat</button>
<button id="sun" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sun">Sun</button>
</div>
</div>
</div>
Gives this on the site
DataTable data
When i do call and get data back from my DataTable it pre-selects the days from the JSON. I have all this working but as i said seems over kill to have to keep repeating the IF just for a different button especially when i have to do this for days '01 - 31'
Jquery
var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',');
splitSelectedDays.forEach(day => {
let val = day.trim();
if(val == 'Mon') {
$('#mon').removeClass('btn-default');
$('#mon').addClass('btn-primary');
}
if (val == 'Tue') {
$('#tue').removeClass('btn-default');
$('#tue').addClass('btn-primary');
}
if (val == 'Wed') {
$('#wed').removeClass('btn-default');
$('#wed').addClass('btn-primary');
}
if (val == 'Thur') {
$('#thur').removeClass('btn-default');
$('#thur').addClass('btn-primary');
}
if (val == 'Fri') {
$('#fri').removeClass('btn-default');
$('#fri').addClass('btn-primary');
}
if (val == 'Sat') {
$('#sat').removeClass('btn-default');
$('#sat').addClass('btn-primary');
}
if (val == 'Sun') {
$('#sun').removeClass('btn-default');
$('#sun').addClass('btn-primary');
}
})
Console.Log of returned data

The technique you want to follow is called Don't Repeat Yourself, or DRY for short.
In this case the day is always the same as the id of the element you want to target, so you can manually build the selector string once from that. You can also use toggleClass() instead of alternate addClass() and removeClass() calls. Try this:
splitSelectedDays.forEach(day => {
let dayName = day.trim().toLowerCase();
$('#' + dayName).toggleClass('btn-default btn-primary');
})

Related

How do you make a button disabled at first when the page is rendered and then it will be enabled when 2 button is pressed

I want to make the third button graph disabled at first and after the first 2 buttons (button1 and button2) is pressed and hidden, third will be enabled and can click on it.
<button type="button" class="btn btn-primary" id="button1" onclick="dataButton1(); this.style.visibility= 'hidden'; this.disabled=true">Data1</button>
<button type="button" class="btn btn-primary" id="button2" onclick="dataButton2();this.style.visibility= 'hidden'; this.disabled=true">data2</button>
<button type="button" class="btn btn-primary " id="button3" onclick="chart1();this.style.visibility= 'hidden'; this.disabled=true">Graph</button>
Have a go with this
const dataButton1 = () => console.log("1")
const dataButton2 = () => console.log("2")
const chart1 = () => console.log("chart 1")
const container = document.getElementById("container");
const buttons = [...container.querySelectorAll("button")];
container.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.id === "button1") {
dataButton1();
}
else if (tgt.id === "button2") {
dataButton2();
}
else if (tgt.id === "button3") {
chart1();
}
tgt.setAttribute("hidden",true); // hide
const show = buttons.map(btn => btn.getAttribute("hidden")); // cannot use hasAttribute here
if (show[0] && show[1] && !show[2]) buttons[2].removeAttribute("disabled");
})
<div id="container">
<button type="button" class="btn btn-primary" id="button1">Data1</button>
<button type="button" class="btn btn-primary" id="button2">Data2</button>
<button type="button" class="btn btn-primary" id="button3" disabled>chart</button>
</div>
First add disable attribute to third button. Then on each click of button 1 and 2 check for hasAttribute("disabled") of other button to see both of them are clicked (and disabled) or not
Here is working sample:
function dataButton1() {
if (document.getElementById("button2").hasAttribute("disabled"))
document.getElementById("button3").setAttribute("disabled", false);
}
function dataButton2() {
if (document.getElementById("button1").hasAttribute("disabled"))
document.getElementById("button3").removeAttribute("disabled");
}
<button type="button" class="btn btn-primary" id="button1"
onclick="dataButton1(); this.style.visibility='hidden'; this.disabled=true">
Data1
</button>
<button type="button" class="btn btn-primary" id="button2"
onclick="dataButton2();this.style.visibility= 'hidden'; this.disabled=true">
data2
</button>
<button disabled type="button" class="btn btn-primary " id="button3">
chart
</button>

Simplify JavaScript code. document.getElementById

I have this code. The goal is to write the number when needed in a specific field. The problem is that the code is large. Can I simplify the code more?
HTML code
<div class="btn-group mr-2" role="group" aria-label="First group">
<button type="button" onclick="e1()" class=" btn">01</button>
<button type="button" onclick="e30()" class="btn">30</button>
</div>
JavaScript code
function e1() {
document.getElementById("epis_n").value = "1";
document.getElementById("order").value = "1";
}
function e30() {
document.getElementById("epis_n").value = "30";
document.getElementById("order").value = "30";
}
You could make a function that takes an argument instead.
HTML:
<button type="button" onclick="e(1)" class="btn">01</button>
...
<button type="button" onclick="e(30)" class="btn">30</button>
JavaScript:
function e(n) {
document.getElementById("epis_n").value = n.toString();
document.getElementById("order").value = n.toString();
}

Calling 2 buttons functions in the same form PHP

I implemented a page with 2 buttons which call 2 different functions on their button clicks. But the any of the buttons are not working. They are just reload the same page. I'll put my code down below.
<form class="form-horizontal" id="add_product_form" method="post">
<script>
function submitForm(action)
{
document.getElementById('add_product_form').action = action;
document.getElementById('add_product_form').submit();
}
</script>
<div class="col-sm-12">
<input type="submit" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="submit" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
</div>
Any help would be really appreciated. Thank you! Add_to_cart function which is mentioned above the page.
function check_add_to_cart(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
return true
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
function check_add_to_quote(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
return true
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
}
You can do following. Change typesubmit to button And as you already have submitForm() method. Call this method when you want to return true.
Change
<input type="submit" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="submit" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
To
<input type="button" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="button" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
And change your js functions to:
function check_add_to_cart(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
//return true
submitForm(""); //you can pass action in this if you want other page
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
function check_add_to_quote(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
//return true
submitForm(""); //you can pass action in this if you want other page
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
}
And remove submitForm() definition between html and add it to script block

Bootstrap datetimepicker changing formats dynamically

I have a function that I'm using to update the format of a Bootstrap datetimepicker when some event happens. The first subsequent time that I click on the datetimepicker, it utilizes the new format to render the picker. For example, if I set the format to YYYY it only shows years. However, if I close the datepicker and open it again, then it renders the full calendar. Am I doing something wrong, or is this a bug with the datetimepicker?
function updateInterval(interval) {
$('#interval').val(interval);
if (interval === 'LAST24') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/DD/YYYY HH:mm:ss');
} else if (interval === 'HOURLY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/DD/YYYY');
} else if (interval === 'DAILY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/DD/YYYY');
} else if (interval === 'WEEKLY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/YYYY');
} else if (interval === 'MONTHLY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('YYYY');
}
}
Based on the documentation it seems pretty straightforward, so not sure what I'd be doing wrong.
Your code is fine, it's a known bug of the lastest version of Eonasdan's bootstrap-datetimepicker. You can try to set currentViewMode = 0; in the component code as suggested in the github link or use an older version, like 4.17.37, as shown in the following working snippet:
var jq182 = $;
function updateInterval(interval) {
$('#interval').val(interval);
if (interval === 'LAST24') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/DD/YYYY HH:mm:ss');
} else if (interval === 'HOURLY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/DD/YYYY');
} else if (interval === 'DAILY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/DD/YYYY');
} else if (interval === 'WEEKLY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('MM/YYYY');
} else if (interval === 'MONTHLY') {
jq182('#endDatePicker').datetimepicker().data('DateTimePicker').format('YYYY');
}
}
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<div class="input-group date" id="endDatePicker">
<input type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<button type="button" class="btn btn-default" onclick="updateInterval('LAST24')">LAST24</button>
<button type="button" class="btn btn-default" onclick="updateInterval('HOURLY')">HOURLY</button>
<button type="button" class="btn btn-default" onclick="updateInterval('DAILY')">DAILY</button>
<button type="button" class="btn btn-default" onclick="updateInterval('WEEKLY')">WEEKLY</button>
<button type="button" class="btn btn-default" onclick="updateInterval('MONTHLY')">MONTHLY</button>
<input type="text" id="interval" class="form-control" readonly>
Here and here people that had the same issue.

Javascript - Toggle Visibility

I am trying to display a button when the input is valid.
It doesn't work, it just displays all the buttons.
Here is the JavaScript:
var toggleVisibility = function ()
{
hasOccurred = validate(textEntry);
if (hasOccurred == false) {
$("addBtn").style.visibility = "visible";
$("deleteBtn").style.visibility = "hidden";
}
else if (hasOccurred == true) {
$("addBtn").style.visibility = "hidden";
$("deleteBtn").style.visibility = "visible";
}
}
This is the HTML for the buttons:
<button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button><br/>
<button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button><br/>
<button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>
You're using the $ as if you're using jQuery (but with incorrect CSS selectors). Without jQuery you need document.getElementById("...")
Note: I changed hasOccurred so that the snippet works.
var toggleVisibility = function() {
hasOccurred = false;
if (hasOccurred == false) {
document.getElementById("addBtn").style.visibility = "visible";
document.getElementById("deleteBtn").style.visibility = "hidden";
} else if (hasOccurred == true) {
document.getElementById("addBtn").style.visibility = "hidden";
document.getElementById("deleteBtn").style.visibility = "visible";
}
}
toggleVisibility();
<button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button>
<br/>
<button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button>
<br/>
<button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>

Categories

Resources