consecutive html() calls overwrites the first - javascript

Here is my jquery
var defaultControlClassic = "<div id='control-textarea-wrapper' class='control'>" + "\n";
defaultControlClassic += "<textarea id='control-textarea' tabindex='1000' rows='1'></textarea>" + "\n";
defaultControlClassic += "<button type='button' class='btn btn-link btn-icon'><i class='material-icons input-send'></i></button>" + "\n";
defaultControlClassic += "</div>" + "\n";
var msg = jsonResponse.html;
intent = jsonResponse.intent;
//Create a dom node out of the response
var div = document.createElement('div');
div.innerHTML = msg.trim();
var domMsg = div.firstChild;
//If Typing animation is happening time to remove it
$('.sender-action').parent('.response').remove();
//Get the Control from the response
var control = domMsg.getElementsByClassName("control")[0];
//Remove the current control from the domMsg
$(domMsg).find('.control').remove();
//Use default control if none specified
if (control === undefined) control = defaultControlClassic;
//Add the control
$('.step-next .controls').html(control);
$('.fixed-control').html(control);
and this works fine with the above text value of "defaultControlClassic"
but when "control" gets assigned by this...
var control = domMsg.getElementsByClassName("control")[0];
The first call to html() works, and so does the second, but but the first gets overwritten by the second one
$('.step-next .controls').html(defaultControlClassic);
$('.fixed-control').html(defaultControlClassic);
Here is the html
<div class="chat-window" >
<header class="chat-header">
<div class="modern-nav d-flex justify-content-between">
<button type="button" class="btn btn-link btn-previous" style="display: none;"><i class="fal fa-long-arrow-left"></i> Previous</button>
<div class="spinner"> </div>
<button type="button" class="btn btn-link btn-restart" style="display: none;">Restart </button>
</div>
<div class="progress" >
<div class="progress-bar" role="progressbar" style="width: 1%;" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100">1%</div>
</div>
</header>
<div class="chat-body">
<div class="step-container">
<form class="step-form step step-next">
<div class="messages" class="" ></div>
<div class="controls" class="" ></div>
</form>
</div>
<div class="fixed-control"></div>
</div>

Sorry guys - it was a confusiong question.
html() is not working unless its actually html - for some reason if its an object it is overwriting
Here is one solution
//Use default control if none specified
if (control === undefined)
control = defaultControlClassic;
else
control = $('<div>').append($(control).clone()).html();

Related

Increasing space between rows in table dynamically created from js function

I have a JS function in a modal that is creating a table in a grid from data being returned from a controller action. It works fine, however I wish there was a little more space between the rows. I have tried adding &nbsp and it doesn't seem to do the trick.
Can anyone give me a solution to this? Below is a picture of the modal, my JS function and the markup for the modal.
modal:
JS function:
$("button[name='paramsBtn']").click(function () {
/* Grabs ID from col selected */
var $col = $(this).closest('.row').find('.requestId');
var jobRequestId = $col.data('id');
var nameType = $col.data('name');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId, "name" : nameType},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var name = [];
var value = [];
var arr = results;
//loop through arr created from dictionary to grab key(s) and value(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
//name += key;
//value += results[key];
name.push(key);
value.push(results[key])
//Remove previous rows
$("div[name='params']").remove();
for (var i in name) {
//Adding parameters as rows
$('<div class="col-md-6 text-break" name="params"> ' + name[i] + '</div>'+ '<div class="col-md-6 text-break" name="params">' + value[i] + '</div>').insertAfter($('#modalGridHeader'));
}
}
}
}
});
});
markup for modal:
<div class="modal fade" id="paramsModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header modal-header-primary" style="margin-bottom:-16px;">
<a class="btn btn-xs btn-primary pull-right" data-dismiss="modal" aria-label="Close"><span class="glyphicon glyphicon-remove"></span></a>
<h4 class="modal-title" id="modalTitleText">Job Parameters</h4>
</div>
<div class="modal-body" style="height:250px;">
<div class="list-group">
<div class="row list-group-item list-group-item-heading container divTableHeading" style="width:inherit; margin-bottom:0px;" id="modalGridHeader">
<div class="col-md-6 font-weight-bold"> Parameter(s): </div>
<div class="col-md-6 font-weight-bold"> Value(s): </div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The line that is adding the rows is:
$('<div class="col-md-6 text-break" name="params"> ' + name[i] + '</div>'+ '<div class="col-md-6 text-break" name="params">' + value[i] + '</div>').insertAfter($('#modalGridHeader'));
Here is where I have tried adding &nbsp. I have also tried adding margin-bottom:5px, but it looked very odd.
Thanks
Quick and dirty
In <div class="col-md-6 text-break" name="params"> add style="height:20px;".

I want to dynamically create a tag by using javascript

I'm using a bootstrap modal.
The Function what I want to dynamically create a button at body tag when I click the modal button.
Description about function what I apply: As soon as I click the bluebutton, I want to create it at the body tag('beside the '+' button')
window.onlaod = function(){
var blue = document.getElementById('blue');
blue.onclick = function(){
blue.onclick = null;
var result = document.getElementById('result');
var newblue = document.createElement('span');
newblue.id = 'newblue';
newblue.innerHTML += '<button type="button" class="btn btn-primary btnWH " id="blue"></button>';
result.appendChild(newblue);
};
};
-> This is the code about event after click the bluebutton.
<!-- label color -->
<div class="modal-body">
<button type="button" class="btn btn-primary btnWH " id="blue"></button>
</div>
-> This is the code about bluebutton.
<div class="card border-secondary mb-3" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<div id="result">
<span id="first">
<button type="button" class="btn btn-primary plusbtn" data-toggle="modal" data-target="#mymodal"> +
</button>
</span>
</div>
</div>
</div>
-> This is the code about '+'button.
This will create a button when click on add button inside div id of result code as follows:
<html>
<body>
<button type="button" id="blue">add</button>
<div id="result"></div>
<script>
window.onload = function() {
return addEvent();
}
function addEvent() {
var blueButton = document.getElementById('blue');
blueButton.addEventListener("click", addButton)
}
function addButton() {
var result = document.getElementById('result');
var newBtn = document.createElement('span');
newBtn.id = 'newblue';
newBtn.innerHTML += '<button type="button" id="blue">test</button>';
result.appendChild(newBtn);
}
</script>
</body>
</html>

Unable to get position of target in ScrollLeft or ScrollTo in ASP.NET JavaScript

I am trying to scroll horizontal <div> by clicking on button and jumping to the position of given element.
I am trying like this:
<input type="button" class="hor" onmousedown="scrollDiv6('MyDiv3', Eve_25)" value=#Model.CalendarDates[i].Date />
var timer6;
function scrollDiv6(divId6, depl6) {
var scroll_container6 = document.getElementById(divId6);
var target = $(document.getElementById(depl6)).position().left;
scroll_container6.scrollTo(target);
//timer6 = setTimeout('scrollDiv6("' + divId6 + '", ' + depl6 + ')', 1);
}
<div class="scrolling-wrapper-flexbox scroller" id="MyDiv3" style="width:100%;position:relative; z-index:2;">
#for (int i = 0; i < Model.HomeEventsList.Count(); i++) {
<div class="card2" style="width:300px;height:400px;" id="Eve_#i">
<div style="text-align:center;">
<h4 style="font-size:30px;text-align:center;" class="center-fit">#Model.HomeEventsList[i].EventName.ToString()</h4>
<div class="featuredImageBox" style="width:280px">
<img height="200" width="280" style="object-fit:cover" src="~/UserFiles/#Model.Owner/min/#Model.HomeEventsList[i].EventFeaturedImage" />
</div>
<div style="text-align:center;">
<span class="center-fit" style="text-align:center;font-size:30px;">
#Model.HomeEventsList[i].EventStart.DayOfWeek.ToString()
#Model.HomeEventsList[i].EventStart.ToString("dd MM yyyy")
</span>
</div>
<div style="text-align:center">
<span class="center-fit" style="text-align:center;font-size:30px;">
#Model.HomeEventsList[i].EventStart.ToString("HH:mm")
#Model.HomeEventsList[i].EventDuration
</span>
</div>
<h4 class="center-fit" style="text-align:center;font-size:30px;overflow-wrap: break-word;word-wrap: break-word;hyphens: auto;">#Model.HomeEventsList[i].EventDescription.ToString()</h4>
</div>
</div>
}
</div>
On button click nothing happens.
How can I scroll to given element on button click?

How do I make JS code not affect other DIV?

Hi I am try to make a list of item, I have "add" and "minus" button for each item. The problem is that the JS code I had control two items together. ex. if I click "add" for item1, then the item2 gets added as well.
Looks like that my JS functions works for all button elements. So when I click a "button" element, all buttons get triggered.
How can I do add them individually?
PS: I guess I need to do something like a specific ID for JS to trigger. My thought is add a unique ITEM ID for each one and trigger the button under that specific ID so other buttons under other ITEM ID don't get triggered.
Here is my HTML code:
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
Here is my JS:
var theTotal = 0;
var theSales = 0;
var minusButton = document.getElementById('minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function () {
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales++;
var num = theTotal.toFixed(2);
$('.total').text("¥" + num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales--;
var num = theTotal.toFixed(2);
if ( theSales == 0 ) {
$('.total').text("");
$('.total-num-of-sales').text("");
$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0 ) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
}
};
});
Don't use multiple id on same page
http://jsfiddle.net/bjc1c9tr/4/
Check this will help you
var theTotal = 0;
var theSales = 0;
var minusButton = $('.minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function(){
var ID = $(this).attr('data');
if (ID == "add") {
$(this).parent().find('.minus').show();
theTotal = Number($(this).parent().find('.num-sales').text()) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text()) + Number(1);
var num=theTotal.toFixed(2);
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number($(this).parent().find('.num-sales').text()) - Number($(this).val());
theSales= Number($(this).parent().find('.num-sales').text()) - Number(1);
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$(this).parent().find('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
$(this).parent().find('.minus').hide();
}
else if ( theSales > 0) {
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales + "份")
$(this).parent().find('.num-sales').text(theSales);
}
};
});
html (added new classes)
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>
$('button').click(function(){
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())+1;
var num=theTotal.toFixed(2);
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())-1;
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
//$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$(this).parent().find('.num-sales').text(theSales);
//$('.num-sales').text(theSales);
}
};
$(this).parent().find('.num-sales').text(theSales);
By this way you can get the parent of clicked button and change the value of .num-sales of the selected parent
https://jsfiddle.net/s2u9eb36/ refer this one
You are mixing the elements because of your id and class selectors.
When you select elements through jQuery by class (like $('.num-sales')), jQuery gives you a collection of all elements that match the selector. In your case, that would be both class="num-sales" elements.
Whenever you then call a function (like .html(theSales)), it will apply that function to each element in the collection, that's why your code is affecting more than one element.
You will need to find a way to distinguish one element of the other. There's quite a few options here, but I like doing it by limiting the scope of my selectors. With this I mean I would first find the food-detail div that contains the clicked element, and then find .num-sales etc... only within that element.
Then you can do the following in your button clicks:
$('button').click(function(){
var ID = this.id;
var element = $(this) //make a jQuery object of the clicked button
// finds the first parent element with class food-detail
var container = element.closest('.food-detail');
// find .num-sales within container
var numSales = container.find('.num-sales')
// continue...
});
in short:
when a button is clicked, find the food-detail div the button is in
.find in only that container instead of using selectors on the entire document
Edit: you should really change the id="Add" and id="minus" on your buttons, ids should be unique on the entire document. You can simply add add or minus as a class instead and check for it with element.hasClass('add').

how to create generic html with javascript

I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.

Categories