JavaScript if statement / displaying a button - javascript

I am trying to workout the following JavaScript if statement:
<script>
if ($crs_date2 != '0000-00-00'){
document.write('No other course date available');
} else {
document.write(<button class='btn btn-danger data-toggle='modal' id='actionButtonOrange'>$crs_date2</button>);
}
</script>
I am encountering two issues:
The button is not being displayed.
the function does not seem to be working as intended.
Essentially what would happen is that if no date is available (by default it displays 0000-00-00 if no date is available but it is not aesthetically pleasing), the JavaScript message appears.

You are missing delimiters around the string:
document.write("<button class='btn btn-danger data-toggle='modal' id='actionButtonOrange'>" + $crs_date2 + "</button>");

Related

onclick attribute of button specified in JavaScript doesn't visible in html inspect

i have made a code where made a button named "Clear Cart" and passes it to the html code via javascript. I added the attribute 'onclick' on that button but when I inspect that button on page then button appears without 'onclick' attribute. All other attributes are appearing okay but 'onclick' attribute is not visible there.
this is my code:
popStr = popStr + "<button id ='clearcart' class='btn btn-primary' onclick='clearCart()'> Clear Cart </button>";
document.getElementById('popcart').setAttribute('data-content', popStr);
This is the output I am receiving
<button id="clearcart" class="btn btn-primary"> Clear Cart </button>```
It looks like your html is "sanitized" (removing the onclick) by the library you are using to inject the new element.
Your question is not clear about how it is added to the DOM from data-content attribute. There should not be any problem if you are setting this HTML from data attribute to DOM with Element.innerHTML
Following is the sample code based on the assumptions:
let popStr = "";
popStr = popStr + "<button id ='clearcart' class='btn btn-primary' onclick='clearCart()'> Clear Cart </button>";
document.getElementById('popcart').setAttribute('data-content', popStr);
function addToDom() {
document.querySelector("#output").innerHTML = document.getElementById('popcart').dataset.content;
}
function clearCart() {
alert("working!")
}
Workign example: https://jsbin.com/tavoyozewa/edit?html,js,output

Cannot add a parameter in a JavaScript function

I cannot add a parameter in the Openpopup() function, when ever i try,i have an error. Need your assistance.
Thanks in advance.
return "<a onclick='return Openpopup()' class='btn btn-info btn-lg clickBtn' data-val='" + data + "'>" + "View Detials" + "</a>";
You can pass data to function like this: below is small example:
$( document ).ready(function() {
var str = "This is testing string";
$("#testing").append("<a onclick='return Openpopup(\""+str+"\")' class='btn btn-info btn-lg clickBtn' data-val='1'> View String </a>")
});
function Openpopup(str) {
alert(str);
}
// html
<div id="testing"></div>
Try:
onclick="return Openpopup(\''yourParameter'\')"
Generally, I would advise to use a JS or Jquery function here though, because this type of formatting quickly gets confusing and is hard to maintain.

.click get a piece of json to appear inside an alert

So I have a get json function that makes items appear on my page, there is a button with json included inside of it that when is clicked I want the item to appear inside an alert (its called cart) - its going to be a simple shopping cart that is hidden on page ready/load. So when the user clicks this button parts of my json file appear inside of the alert, like a shopping cart, If there can be a total to calculate the price this would be good but is not necessary.
So this is my script to get the json and display it on my page :
$.getJSON('iproducts.json',function(products){
var output = "";
$.each(products.appleitems, function(i, product) {
output +=
"<div class=\"col-xs-12 col-sm-6 col-md-3\"><div class='panel panel-default'><div class='panel-footer'><h4 class='text-center'>"
+ products.appleitems[i].Product_id
+ "</h4></div>" + "<img src ='" + products.appleitems[i].Imgpath + "' style='width:100%;height:250px; display: block;' id='appleinfo_"
+ products.appleitems[i].Product_id +
"' /><p class='lead text-justify'>" + products.appleitems[i].Information
+ "</p><div class='panel-footer'><button class='btn btn-primary btn-block' id='btncart'>£" + products.appleitems[i].Price+"</button></div></div></div>";
});
$("#container").html(output);
});
as you will notice this is the button I am talking about:
<div class='panel-footer'><button class='btn btn-primary btn-block' id='btncart'>£" + products.appleitems[i].Price+"</button></div>
the price is displayed inside of the button.
This is a snip (one of the products, there are about 12 products in total) from my json file:
{
"appleitems":[
{
"Product_id":"Iphone5",
"Information":"Iphone 5 64GB",
"Imgpath":"image/iphone5.jpg",
"Price":"200.00"
}
]
}
This is the alert I want the name and price to display in when the button is clicked:
<div class="alert alert-warning" id="cart"></div>
Here is a bit of a clue from a previous script I worked on, when the user entered their name/ login details (from the json) and they matched their name, picture and details would appear in the welcome alert, I also had a hide button inside this alert that then hid the welcome alert and this is how I got it to work ( could be quite similar to this only .show():
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
Kind Regards
So on button click you want to update the alert div with it's price.
Here is a code block explaining things you need.
According to this html
$('.btn-block').click(function(e){
//alert($(this).attr("value")); //get value of button
$("#cart").empty(); //clear div every time on click
$("#cart").html($(this).attr("value")); //this will update div with value of button.
var product_information = $(this).closest("div").prev("p").html();//This will get you product info
});
I have added some explanation as comment.This are self explanatory.
Important
I notice you assign hardcore id in each loop in button which is not correct.You should always assign dynamic id as id cannot be same.

Error passing json array onclick- html and javascript

I am generating a clickable list dynamically using jquery. here is the code that generates the list.
for(dayint=0;dayint < day_arr.length;dayint++){
var temp_pass = JSON.stringify(day_arr[dayint]);
//alert(temp_pass);
$("#itin_list").append('<b>Day '+ dayint + ' of Trip from '+ start_n +' to '+ end_n +' </b> <button data-toggle="modal" data-target="#dirModal" style="position:absolute;bottom:5px; right:5px;float:right" class="btn btn-primary">Show Directions</button><br>');
}
The problem I have is when passing the json array to my sethidddendiv function. The code sample for the function is as below:
window.sethiddendiv = function(str) {
//var nisal = $.parseJSON(str);
alert(str);
}
When the list item is clicked, instead of giving the json array, it alerts "undefined" all the time.
Here is the html that is generated in the page when I inspect element:
<b>Day 0 of Trip from Colombo to Kandy </b> <button data-toggle="modal" data-target="#dirModal" style="position:absolute;bottom:5px; right:5px;float:right" class="btn btn-primary">Show Directions</button>
What could be the issue here?
I already tried using single quotes for the onclick, but it didnt work. Any help would be very welcome. I'm stuck.

Javascript function sending html object

I'm using Jquery Datatables.
I have the following code as one of my rows in aaData
case "opties" : $row[] = ("<button onclick='btnselecteer()'
style='margin-left:5px;' class='btn grey btn-xs tooltips btn-selecteer' data-original-title='Selecteer/Deselecteer' data-placement='top' data-container='body'>
<i class='fa fa-check'></i></button>");
break;
Which gives me a button in one of my table rows
Now I can't use
$(".btn-selecteer").on('click... so I'm using it with a function. I just can't figure out how to send the button somehow so I can make adjustments to it ( adding/removing a class)
Just send over this and then you access it:
<button onclick='btnselecteer(this)'
Then for your js:
btnselecteer(btn) {
$(btn).addClass('clicked');
}

Categories

Resources