i want to update rooms rate which is shown on screen shot. when i click on edit room rate it hide existing button and show text box containing existing room value . when i fetched this data using while loop in php it works only on first element. please help me
used javascript as bellow
<script>
function hide_editbtn()
{
var rmrate = document.getElementsByClassName("roomrate");
for(var i = 0; i < rmrate.length; i++){
rmrate[i].style.display = "none";
rmrate[i].disabled = true;
}
var updbtn = document.getElementsByClassName("updateratebtn");
for(var i = 0; i < updbtn.length; i++){
updbtn[i].style.display = "none";
rmrate[i].disabled = true;
}
}
function show_editbtn()
{
var rmratelink = document.getElementsByClassName("roomratelink");
for(var i = 0; i < rmratelink.length; i++){
(function(index){
rmratelink[i].onclick = function(){
document.getElementById("roomrate").style.display="block";
document.getElementById("roomrate").disabled = false;
}
})(
}
}
</script>
Used html Content as bellow
<div class="card-stacked order-sm-1 newelmnt">
<div class="card-body pt-sm-0 pb-0 px-0 pr-sm-6 pr-md-8">
<p> </p>
<h3 class="card-title font-weight-normal text-truncate elconnt">
Ac Room
</h3>
<div class="d-flex align-items-baseline price mb-1">
<span class="d-block text-primary font-weight-500 display-5 mr-1">Rs.<label id="hotelroomrate">1500</label> <span class="btn-group-toggle roomratelink" data-toggle="buttons" onclick="show_editbtn()" id="roomratelink" style="margin-top:10px;">
<label class="btn btn-xs btn-outline-primary mb-2">
<input type="checkbox"> Edit Room Rate
</label>
</span>
</span>
<label class="sr-only" for="user-name"> </label>
<input type="text" class="form-control roomrate" id="roomrate" aria-describedby="user-name" placeholder="Modify Room Rate" style="width:180px;padding-right:10px;"/>
<span class="btn-group-toggle updateratebtn" data-toggle="buttons" id="updateratebtn" >
<label class="btn btn-outline-primary mb-2" style="background:#512da8;color:#fff;margin-top:5px;">
<input type="checkbox"> Submit
</label>
</span>
</div>
</div>
</div>
screen shot
i want to update rooms rate which is shown on screen shot. when i click on edit room rate it hide existing button and show text box containing existing room value . when i fetched this data using while loop in php it works only on first element. please help me
You could try removing the listener because you just wanna show the buttons.
Second, use class instead of an ID for the elements. IDs are unique. So when you loop it only the first occurence will be handled.
Make the #roomrate ID a class .roomrate.
for(var i = 0; i < rmratelink.length; i++){
let btn = rmratelink[i].getElementsByClassName('roomrate')[0];
btn.style.display="block";
btn.disabled = false;
}
Hope it helps
Related
I have this function which uses innerHTML to insert html into a div:
function displayInputIntro() {
var submitbutton = document.getElementById('submitbutton')
var intro = document.getElementById('Intro')
var introNewSection = document.getElementById('intro-row')
var uniqueID = ""
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var length = 7
for (var i = length; i > 0; --i) uniqueID += chars[Math.floor(Math.random() * chars.length)];
uniqueID = uniqueID
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id=' + uniqueID + '><div class="card z-index-2"> <div class="card-body p-3" style="margin-top: -20px;"> <h6 class="ms-2 mt-4 mb-0">Intro <i class="fa fa-times" style="color: gray;"></i></h6> <p class="text-sm ms-2">Section 1</p> <div class="container border-radius-lg"> <div class="row"> <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea> </div> </div> </div> </div></div>'
submitbutton.style.display = ''
}
and then my html:
<div class="row mt-4" id="intro-row"></div>
however, as you can see in the introNewSection.innerHTML, I have a <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea>
the problem is, this function displayInputIntro() can be triggered multiple times. Every time its triggered, and there's any text inside the textarea, it just clears it and I don't know why. how can I fix this?
First thing you need to close the HTML tags properly, is not closing properly , i see is not having closing tag while assigning html to innerHTML, Second thing whenever you are using innerHTML it will override the html content.
If you want to inject the html then use insertAdjacentHTML tag and execute as below
introNewSection.insertAdjacentHTML('afterend', 'additional HTML code');
Note: You should find out why the function is triggering multiple times.
I've created few buttons, and when clicked I want to affect the final cost, working but not as it should be. The button has a value and the final value of cost doesn't work, can someone let me know what I'm doing wrong?
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].click) {
total += parseFloat(input[i].value);
}
}
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
}
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
But when I pick one, the final price won't work perfectly. is displaying a different number! can some help me?
Attach the click event to all the buttons and add the cost on every click like the snippet below shows.
NOTE : If you want to add the cost just one time by button you could disable the button immediately after the click using :
this.setAttribute('disabled','disabled');
Hope this helps.
var products = document.querySelectorAll(".buttonBg");
for (var i = 0; i < products.length; i++) {
products[i].addEventListener("click", totalIt);
}
function totalIt() {
var total = document.querySelector("#total");
var currentVal = parseInt( total.innerText );
var new_val = parseInt( this.value );
if( this.classList.contains('clicked') ){
total.innerText = ( currentVal - new_val ).toFixed(2);
}else{
total.innerText = ( currentVal + new_val ).toFixed(2);
}
document.querySelector("#total2").innerText = total.innerText;
this.classList.toggle('clicked');
}
.clicked{
color: green;
}
<div class="priceWrapper">
<h3 class="priceText1">$<span id="total">0.00</span></h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
<h3 class="priceText1">$<span id="total2">0.00</span></h3>
I have adapted your code to make this work see below
Note below i have added id's to the product buttons.
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" id="product1" name="product" value="25.00" type="button">
Producto 3
</button>
</label>
<label>
<button class="buttonBg" id="product2" name="product" value="10.00" type="button">
Producto 4
</button>
</label>
</form>
</div>
Then i have modified your code
//
// this will be the element clicked so just add it, as below
//
function addProduct() {
el = this;
total += parseFloat(el.value);
total_el.innerText = "$" + total.toFixed(2);
};
//
// Cache your total get a reference to the total element (faster!)
// when you write your code don't keep doing stuff when it can be done
// once - speed is everything and as you write more complex stuff
// doing it write from day one will pay off in your work (toptip)
//
var total = 0;
var total_el = document.querySelector(".priceText1");
//
// Bind up the click event
//
document.getElementById('product1').onclick = addProduct;
document.getElementById('product2').onclick = addProduct;
And here you can see the end result
https://jsfiddle.net/64v3n1se/
To scale this you would add the click handler using a class and a loop but for simpleness i have... kept it simple.
Because during your calculation you are getting all button's values and add them up so whenever the button is clicked you calculate the sum of the values of the buttons.
Your way of thinking right now, as far as I can tell, is wrong.
You can change your html code and script code like this.
With this way we are passing object of button to the function and we increase the global total variable within the function. Later on you change the dom.
var total = 0;
function totalIt(obj) {
total = total + parseFloat(obj.value);
document.querySelector(".priceText1").innerText = "$" + total.toFixed();
}
And pass the object of button in the html with
<button class="buttonBg" name="product" value="10.00" type="button" onclick="totalIt(this)">
I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/
I would like to know how can I create textboxes and insert data at page load.
What I'm trying to do is open an array string from a database, create the textboxes and populate the textboxes at page load.
I have an array string from an ms sql database that looks something like this
test,test;bla;bla2;test44;test55;test66
I separated each individual array with ; and I would like to create textboxes and insert the values into a textbox, one-by-one, so the end result would look like this:
I don't know how to do it using the code below.
Whatever I try I mess up the add/remove functions or I end up cloning all textboxes when the plus button is clicked.
THANKS
SEE CODE BELOW OR GO TO https://jsfiddle.net/kj3cwww0
<script type='text/javascript'>//<![CDATA[
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('#template_add_form'),
formArray = [ clone($template) ], // init array with first row
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
updateForm(); // first init. of form
});
//]]>
</script>
<script id="template_add_form" type="text/template">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</script>
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
FORM SUBMIT CODE:
<body>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
......the rest of the existing code goes here...
</div>
</form>
</body>
CALLING IT VIA CLASSIC ASP:
if strComp(Request.Form("action"), "submit")= 0 then
Response.write("IT WORKS")
end if
Here is a solution that works :
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
formArray = [ ], // init array enpty
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
$('#template_add_form').remove();
});
.entry:not(:first-of-type)
{
margin-top: 10px;
}
.glyphicon
{
font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
<div id="template_add_form" type="text/template" style="display: none;">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</div>
</form>
</body>
Here's what I changed to your code :
Changed the template which was a <script> to a <div>, and hid it by default using style="display: none;" :
<div id="template_add_form" type="text/template" style="display: none;">
Initialized array empty, so that we can put our own first line : formArray = [ ],
Created a function to add a string in the form :
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
At the end, I added some example data, then pushed an empty line and updated the form :
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
EDIT : I also deleted the template div at the end so that it isn't taken into the form when you submit :
$('#template_add_form').remove();
To be able to do that, I cloned it entirely at start :
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
I use a 3rd party shopping module for this site and hence i cannot tinker with the sourcecode of this module.
Everthing works fine but here is my issue.
On the checkout option the summary contains field which are redundant and i want to hide this fields.
Discount: GBP £0.00
Sub total: GBP £90.00
Shipping: GBP £10.00
Handling: GBP £0.00
Total: GBP £100.00
As you see above only 3 fields have values. I want to use Javascript and hide the fields which do not have any values like "Discount", "Shipping" and "Handling".
Here is a Fiddle to my code
Here is my code
<div class="CartTotalAmountContainer">
<div class=" TotalSalesOrderDetailDiscountAmount">
<div>
<label> <span>Discount:</span>
</label>
</div> <span>GBP £0.00</span>
</div>
<div class="SubTotalAmount">
<div>
<label> <span>Sub total:</span>
</label>
</div> <span>GBP £90.00</span>
</div>
<div class="TotalShippingAmount">
<div>
<label> <span>Shipping:</span>
</label>
</div> <span>GBP £10.00</span>
</div>
<div class="TotalHandlingAmount">
<div>
<label> <span>Handling:</span>
</label>
</div> <span>GBP £0.00</span>
</div>
<div class="TotalAmount">
<div class="dnnLabel">
<label> <span>Total:</span>
</label>
</div> <span>GBP £100.00</span>
</div>
</div>
No my logic is i can access the topcontainer of the elements by using
var X= document.getElementsByClassName("CartTotalAmountContainer");
but how do i access the data inside the individual spans and make the style="display:none" for their parent divs.
Try .querySelector:
var x = document.querySelectorAll(".CartTotalAmountContainer > div > span");
for(var i=0; i<x.length; i++) {
if(x[i].innerHTML == "GBP £0.00") {
x[i].style.display = "none";
}
}
Demo!
And here's some reading for ya: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
Here is a complete native JS solution which works in IE8 and below: jsFiddle: http://jsfiddle.net/giri_jeedigunta/46QyE/
var outerDiv = document.getElementsByTagName('div'),
cartContainer, i,
j,
cartInnerContent;
// Since getElementsByclassName doesnt work in IE8:
for(i = 0; i < outerDiv.length; i++) {
if(outerDiv[i].className === 'CartTotalAmountContainer') {
cartContainer = outerDiv[i];
cartInnerContent = cartContainer.getElementsByTagName('div');
break;
}
}
// Queryselector have limitations in IE8 and below
for(j = 0; j < cartInnerContent.length; j++) {
if(typeof cartInnerContent[j].getElementsByTagName('span')[1] !== 'undefined') {
var spanContent = cartInnerContent[j].getElementsByTagName('span')[1].innerHTML,
priceSplit = spanContent.split('£')[1].split('.')[0];
console.log(priceSplit);
if(parseInt(priceSplit) === 0) {
cartInnerContent[j].style.display = 'none';
}
}
}