Why val() function doesn't work with later rendered html? - javascript

so I have an add minus button rendered with javascript because I needed data from a database and if I don't render it with javascript it will work but it doesn't work.
HTML:
<div id="cart">
<div class="row">
</div>
</div>
JS (rendering):
var output = [];
var food_template = [];
//res is the data got from database
for(var f in res) {
id = res[f]["id"];
name = res[f]["name"];
description = res[f]["description"];
price = res[f]["price"];
food_template = [
'<div class="col-6">',
' <div class="single_food_item media">',
' <div class="media-body", style="margin-right:10px; margin-top: 20px; height: 200px">',
` <h3>${name}</h3>`,
` <p>${description}</p>`,
` <h5>$${price}</h5>`,
//add minus button starts
' <div class="input-group" style="width:50%">',
' <span class="input-group-btn">',
' <button class="btn btn-danger btn-minus" type="button">-</button>',
' </span>',
' <input type="text" class="form-control no-padding add-color text-center height-25" maxlength="3" value="0">',
' <span class="input-group-btn">',
' <button class="btn btn-success btn-plus" type="button">+</button>',
' </span>',
' </div>',
//add minus button ends
' </div>',
' </div>',
'</div>'
];
output.push(food_template.join("\n"));
}
("#cart .row").html(output.join("\n"));
JS (add minus button):
$('#cart .row').delegate('.btn-minus', 'click', function(){
$(this).parent().siblings('input').val(parseInt($(this).parent().siblings('input').val()) - 1);
});
$('#cart .row').delegate('.btn-minus', 'click', function(){
$(this).parent().siblings('input').val(parseInt($(this).parent().siblings('input').val()) + 1)
});
(all functions are called)
What I test made me think that the problem is probably the val() function isn't changing the value of the input HTML since if I use console.log to show it it works but it doesn't update on the web

I think you have both the plus and the minus event handlers attached to the minus button, so when you click it, the plus handler increments the value and the minus handler decrements it, therefore you see no change regarding the value of the input

Related

Adding div on click only once and allowing customer to delete it and reclick it

I'm trying to make a button that when clicked displays only one div. If the user chooses they can click on the remove button and the data in any fields will be cleared and the text inside the div deleted. If a user chooses they can click the button again to bring back the div but cannot create the div more than once. I can make the initial div appear like its suppose to but beyond that I'm stuck.
Here is a list of things I've tried
$(document).on('click', '.remove', function(){
$document.getElementById("demo") .remove('.innerHTML');
$(document).on('click', '.empty', function(){
$('#demo').empty();
});
});
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = '<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>';
}
$(document).on('click', '.empty', function() {
$('#demo').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Add Renters</button>
<p id="demo"></p>
</body>
</html>
You're close check those steps to achieve what you want :
Add type="button" to your button to prevent the submit when you click.
Remove the inline onClick attribute and attach the click event from the JS code.
Check inside myFunction() function if the demo is empty or not before adding the content.
Attach another click event using event delegation on() (since the element was added dynamically to the DOM) to the button with .remove class to remove the content.
NOTE : Since you're using jQuery prevent the mix with vanillaJS like this line :
document.getElementById("demo").innerHTML = ...
Will be better to be :
demo.html(...)
$('button').on('click', myFunction);
$('body').on('click', '.remove', function() {
$('#demo').empty();
});
function myFunction() {
var demo = $('#demo');
if (!demo.html().length) {
demo.html('<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button type="button">Add Renters</button>
<p id="demo"></p>
</body>
</html>

How to color a specific text using regular expression

I'm new to regular expression and I can't understand it well on how it works. It solves my first issue from here. But my problem now is that I want to color the two string separately. The other one is orange and other one is green. But code below is it color the text into orange. And for the or word it is possible to color it as black?.
var str = 'A2 Award Notice or A2 Lease Contract';
var row = '<div class="row mt-2" style="font-size:20px">'
+ '<div class="col-md-1"><input class="chckDocument form-control flat" type="checkbox" style="height:20px; -webkit-box-shadow:none" class="form-control flat mt-2"> </div >'
+ '<div class="col-md-1"> <input type="file" data-type="" data-name="" id="' + 1 + '" class="btnClickHello d-none" value="Upload"><label for="' + 1 + '" class="btn btn-default">Upload</label></div>'
+ '<div class="col-md-10"> ' + str.replace(/(.+?)( or |$)/g, '<a style="color:orange">$1</a> <a style="color:green">$2</a>') + ' </div >'
+ '</div >';
$("#divID").append(row);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divID"></div>
Expected Output
A2 Award Notice <<-- color (green or orange)
or <<-- color black
A2 Lease Contract <<-- color (green or orange)
You need two .replaces - a single one isn't enough, at least not without a callback function. First surround everything outside the ' or 's with your as, and then .replace the resulting string again: search for / or /g and replace with something like <span style="color:black">$&</span>, which will replace all instances of ' or ' with that ' or ' enclosed in a <span>.
That takes care of the or. For the other parts of the string, a plain regular expression alone won't work (at least not in Javascript) - to replace with something different on each match, declare an array of the colors you want to be able to use, and use a callback function that takes an item from the colors array to set as the color:
var str = 'A2 Award Notice or A2 Lease Contract';
const colors = ['green', 'orange'];
const replacedStr = str
.replace(/(.+?)( or |$)/g, (_, g1, g2) => {
const [color] = colors.splice(0, 1);
return `<a style="color:${color}">${g1}</a>${g2}`;
})
.replace(/ or /g, '<span style="color:black">$&</span>');
console.log(replacedStr);
var row = '<div class="row mt-2" style="font-size:20px">' +
'<div class="col-md-1"><input class="chckDocument form-control flat" type="checkbox" style="height:20px; -webkit-box-shadow:none" class="form-control flat mt-2"> </div >' +
'<div class="col-md-1"> <input type="file" data-type="" data-name="" id="' + 1 + '" class="btnClickHello d-none" value="Upload"><label for="' + 1 + '" class="btn btn-default">Upload</label></div>' +
'<div class="col-md-10"> ' + replacedStr + ' </div >' +
'</div >';
$("#divID").append(row);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divID"></div>

jQuery dynamic fields after validation are disappearing

I have a problem with my jQuery and with validation.
Here is my Code:
var fielddd = 1;
$(document).on('click', '.btn.add-field', function() {
fielddd++;
$('#newfield').append('<textarea class="from-control" name="somename[]" id="field_' + field + '"></textarea>' + '<button class="btn add-field">add</button>' + '<textarea class="from-control" name="somename2[]" id="field_' + field + '"></textarea>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<textarea class="from-control" name="somename[]" id="field"></textarea>
<button class="btn add-field">add</button>
<textarea class="from-control" name="somename2[]" id="field"></textarea>
</div>
<div class="row" id="newfield">
<!-- new textarea -->
</div>
The problem is that I have an validation and I have an button submit, after checking that one field empty is, the code make and redirect and after this redirect to the same page so that user can give his parameter in textarea. But after this redirect, by the user added field are disappeared.
How can I fix it?
You are using the same id in each and every textarea. Id must be unique. Mistakenly you are using "field" which must be replaced with "fielddd" that is being incremented.
var fielddd = 1;
$(document).on('click', '.btn.add-field', function() {
fielddd++;
$('#newfield').append('<textarea class="from-control" id="field_' + fielddd + '"></textarea>' + '<button class="btn add-field">add</button>' + '<textarea class="from-control" id="field_' + fielddd + '"></textarea>');
});

How to reset the error number when deleted from list

I'm creating a set of textboxes and some drop downs using jQuery. The add function is working with out any issues.
My problem is with the delete function function works nicely as long as the user deletes one after the other but if the user delete from some where else the number sequence get messed up. Which breaks the 1,2,3,4 ... etc and sets the number which was deleted last.
As an example if the user deletes number 4 out of 7 errors the functions sets the last number as 4 when the user clicks the add button the next number generated will be 5 not the correct last number. I want to rest the rest of the numbers when something get removed from the middle.
I'm storing the last number in a hidden filed called stValue which is getting reset when deleting.
My problem is here I can't get my head around to think of way to reset this when deleting from some where else and then reset the entire error number row numbers when something get removed from the middle. Can you guys help me with this below is my code.
jsFiddle will help to understand better
JQuery:
//Add and remove function for the error text boxes
$(document).ready(function () {
$(document).on('click','.addRow',function () {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/);//Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_'+btnId).prop("disabled", true);//Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function () {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
alert(errNoList);
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_'+errNoList).prop('disabled',false);// Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
});
});
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1)+2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="'+genNum+'" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_'+genNum+'" data-bid="addRow_'+genNum+'" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_'+genNum+'" data-bid="delRow_'+genNum+'" value="Delete"/><br />'
}
HTML:
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%"/>
<input type="hidden" value="1" id="stValue"/>
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add"/>
</div>
</div>
</div>
**UPDATE:**Completely changed the code now it's much more simpler adding the solved answer here so it might help some one in the future.
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var btnId = $("#stValue").val(); //Read the value of stValue
btnId = btnId - 1; //Deduct 1 from the value to get the last ID
//Enables the 1st add button if the value equals 1
if (btnId === 1) {
$('#addRow_' + btnId).prop('disabled', false);
}
$(this).parent().remove(); //Remove the text row from the list.
resetErrorNo(); //Calls the reset function
});
});
//Reset the entire error count number index
function resetErrorNo() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
$("#stValue").val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>
Try with whenever, you delete any row, update all input with new number.
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
Full Code
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_' + errNoList).prop('disabled', false); // Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
rearrange();
});
});
function rearrange() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>

dynamic Accordion post and answer

I have this fiddle
http://jsfiddle.net/nesreen/m5TMF/763/
$("#AddansId").click(function(){
//get the parent of the div with id(Collapse+x)
// to abend the data content of the textarea beside the word
//Account Registeration at PrepBootstrap
});
I can create a dynamic accordion with button
inside each accordion I need to make another textarea and button to add another texts in the same collapse
but I face the problem of how can I get the parent of the button in each time even if the parent id is dynamic also
Let's see. A few steps to take here:
First you need to bind the click a bit differently(event
delegation) in this case because you want to click on dinamically
added elements
Second, we get the parent id using closest() method and attr('id')
For getting the textarea value you can use
$(this).parent().prev().find('textarea').val()
and then use append() method to append the text next to the word you want and finally use $(this).closest('.container').append(answer); to add the textbefore the word(this was a bit unclear so I added it before Account Registeration at PrepBootstrap. I hope that is what you meant)
var x = 1;
$(document).on('click', "#AddansId", function() {
var idOfParent = $(this).closest('.panel-collapse').attr('id');
//console.log(idOfParent);
var answer = $(this).parent().prev().find('textarea').val();
$(this).closest('.container').append(answer);
});
$(document).on('click', '#AddQuestId', function() {
x = x + 1;
$("#accordion").append('<div class="panel panel-default">' +
'<div class="panel-heading">' +
'<h4 class="panel-title"> ' +
'<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse' + x + '">' + $("#comment").val() + '</a> </h4>' +
'</div>' +
'<div id="collapse' + x + '" class="panel-collapse collapse in">' +
'<div class="panel-body">' +
'<div class="container"> ' +
' <form>' +
'<div class="form-group" >' +
'<label for="comment">answer:</label>' +
'<textarea class="form-control" rows="5" id="answer' + x + '"></textarea> ' +
' </div>' +
' <div style="float: right;"> <input type="button" class="btn btn-info" value="answer" id="AddansId"></div>' +
'</form>' +
'</div>' +
'Account registration at <strong>PrepBootstrap</strong>' +
'</div>' +
'</div>' +
'</div>' +
'</h4>' +
'</div>');
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="container">
<form>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<div style="float: right;"> <input type="button" class="btn btn-info" value="Add Question" id="AddQuestId"></div>
</form>
</div>
<div class="panel-group" id="accordion">
</div>

Categories