I've created a clone function on html file. But there's a weird error in code. when I put two ending 'div' in same line, the JavaScript code just work fine. but when I beautify html code or put the last ending tag in another line, the JavaScript just doesn't work. please look at the commented line
<body>
<div class="container">
<div class="col-2 m-3 bg-primary" id="show">working</div>
<button id="bt" class="btn btn-outline-primary ml-4 mt-2" onclick="hide()">remove</button>
<div id="error" class="text-danger ml-3"></div>
<div id="myList" style="list-style-type:none;" class="mt-3">
<div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Recipient's username"
aria-label="Recipient's username" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon2"
onclick="removeIt()">X</button>
</div>
</div>
</div></div> <!-- this line is causing issue -->
<button onclick="addElement()" class="btn btn-outline-primary ml-4 mt-2">Add</button>
<div class="form-check">
<label class="form-check-label" for="numbers">
Number Of Row
</label>
<input type="number" class="form-input" name="" id="numbers" value="1">
</div>
<button onclick="passNumber()" class="btn btn-primary btn-lg" >Go</button>
</div>
<script>
let error = document.getElementById('error');
function passNumber(){
let numbers = document.getElementById('numbers').value;
for(let i = 1; i <= numbers; i++){
addElement();
}
}
function hide() {
document.getElementById('show').style.display = 'none';
}
function addElement() {
error.innerHTML = '';
let item = document.getElementById('myList').lastChild;
let cln = item.cloneNode(true);
document.getElementById('myList').appendChild(cln);
}
function removeIt() {
let list = document.getElementById('myList');
if(list.childNodes.length == 2){
error.innerHTML=`you cant delete the last input box`;
}else{
let length = list.childNodes.length;
list.removeChild(list.childNodes[length-1]);
}
}
</script>
this code works fine. but when I change the code into below lines, then the JavaScript just don't work at all -
<body>
<div class="container">
<div class="col-2 m-3 bg-primary" id="show">working</div>
<button id="bt" class="btn btn-outline-primary ml-4 mt-2" onclick="hide()">remove</button>
<div id="error" class="text-danger ml-3"></div>
<div id="myList" style="list-style-type:none;" class="mt-3">
<div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Recipient's username"
aria-label="Recipient's username" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon2"
onclick="removeIt()">X</button>
</div>
</div>
</div>
</div> <!-- this line is causing issue -->
<button onclick="addElement()" class="btn btn-outline-primary ml-4 mt-2">Add</button>
<div class="form-check">
<label class="form-check-label" for="numbers">
Number Of Row
</label>
<input type="number" class="form-input" name="" id="numbers" value="1">
</div>
<button onclick="passNumber()" class="btn btn-primary btn-lg" >Go</button>
</div>
<script>
let error = document.getElementById('error');
function passNumber(){
let numbers = document.getElementById('numbers').value;
for(let i = 1; i <= numbers; i++){
addElement();
}
}
function hide() {
document.getElementById('show').style.display = 'none';
}
function addElement() {
error.innerHTML = '';
let item = document.getElementById('myList').lastChild;
let cln = item.cloneNode(true);
document.getElementById('myList').appendChild(cln);
}
function removeIt() {
let list = document.getElementById('myList');
if(list.childNodes.length == 2){
error.innerHTML=`you cant delete the last input box`;
}else{
let length = list.childNodes.length;
list.removeChild(list.childNodes[length-1]);
}
}
</script>
lastChild is the last child node of any kind, including text nodes. By moving the closing </div> tag, you're adding a text node.
You could use lastElementChild instead to get only the last element in the list.
Here's a simplified example:
console.log(document.getElementById("container1").childNodes.length); // 2
console.log(document.getElementById("container2").childNodes.length); // 3
<div id="container1">
<div>x</div></div>
<div id="container2">
<div>x</div>
</div>
Side note: Your HTML is invalid. div elements cannot be direct children of ul elements. ul elements are expected to contain li elements as their only direct (element) children.
Related
I am working with a chat application. I need to put an input search box for the user to search for a friend from his friends list. I have written code to get ID values and and trigger it onkeyup. However, I am getting an uncaught reference error of function(name) is undefined. Here I am getting users list from server side using socket code.
Function in JS file
$scope.searchFn = function () {
var input, filter, ul, li;
input = document.getElementById("input");
// filter = input.value.toUpperCase();
ul = document.getElementById("list");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display =
"none";
}
}
}
HTML
<main>
<div class="container-fluid">
<input type="hidden" id="user" value="<%= user.username %>" />
<div class="row">
<div class="col-sm-4">
<div class="panel panel-success">
<div class="panel-heading">
<form action="/action_page.php" method="get">
<div class="input-group form-group">
<input id="input" class="form-control" name="browser" placeholder="Search friend.." ng-model="search" onkeypress="searchFn()">
<span class="input-group-btn">
<button class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<h4 align="center">Friends</h4>
</div>
<div class="panel-body" id="scrl1">
<ul id="list"></ul>
</div>
<div class="panel-footer">
<p id="typing"></p>
</div>
</div>
</div>
<div class=".space"></div>
<div class="col-sm-8">
<div class="panel panel-success">
<div class="panel-heading">
<h4 id="frndName" align="center">Chat Room</h4>
<a ng-click="clearchat()">
<span class="glyphicon glyphicon-trash" style="float:right;margin-top:-4%"></span>
</a>
</div>
<div class="panel-body" id="scrl2">
<p id="loading" align="center">Loading.....</p>
<p id="noChat" align="center">No More Chats To Display.....</p>
<p id="initMsg">!!...Click On User Or Group Button To Start Chat...!!</p>
<ul id="messages"></ul>
</div>
<div class="panel-footer input-group" style="width:100%">
<form id="chatForm" action="" onsubmit="return false">
<input id="myMsg" class="input-box-send form-control" ng-model="message" autocomplete="off" style="width:80%" placeholder="Write Message Here.." />
<button type="submit" id="sendBtn" class=" btn btn-primary " ng-disabled="!message" name="btn"><span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
Don't use function expression $scope.searchFn = function () {}.
Function expressions in JavaScript are not hoisted.
Use named functions to avoid such cases
function searchFn() {...}
You are not using an angular directive for triggering the keypress event. The "onkeypress" is an html attribute so any function declared on $scope will not be accessible. You should use ng-keypress directive.
Before:
<input id="input" class="form-control" name="browser" placeholder="Search friend.." ng-model="search" onkeypress="searchFn()">
After:
<input id="input" class="form-control" name="browser" placeholder="Search friend.." ng-model="search" ng-keypress="searchFn()">
I have a modal that allows users to 'refuel' by filling out a form where they can input the amount of fuel to add, however the maximum fuel amount is 180 litres, so if the existing fuel is 170 litres (the existing fuel value will be retrieved from a database), and the user tries to add 20 litres, it should produce an error. I've got some code already, but it's not producing the error. If anyone could point out the issue it would be greatly appreciated.
$(document).ready(function() {
$('#fuel').blur(function() {
if (!ValidateFuel()) {
e.preventDefault();
}
});
$('#auth_form8').on('submit', function(e) {
if (!ValidateFuel()) {
e.preventDefault();
}
});
});
function ValidateFuel() {
var IsValid = false;
var fuel_to_add = $('#fuel').val();
var current_fuel = '100'; // this value will be retrieved from database
var fuel_once_added = Number(current_fuel) + Number(fuel_to_add);
if (fuel_once_added > 180) {
$('#alertInvalidFuel').show();
IsValid = false;
} else {
$('#alertInvalidFuel').hide();
IsValid = true;
}
return IsValid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-success" role="button" data-target="#confirm-refuelG-EEGU" data-toggle="modal"><em class='fa fa-plus'></em></a>
<div id="confirm-refuelG-EEGU" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Fuel G-EEGU</h4>
</div>
<div class="modal-body">
<form name="auth_form8" id="auth_form8" method="post" action="action_refuel.php">
<p>This action cannot be undone.</p>
<hr>
<input class="form-control" id="aircraft_id" name="aircraft_id" value='1' type="hidden">
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">
Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
<div style="display:none;" class="alert alert-danger" id="alertInvalidFuel">
<p>Fuel will exceed 180 litres.</p>
</div>
<hr>
<div class="form-group has-feedback" name="auth_code8" id="auth_code8">
<label for="auth_code8" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input8" autocomplete="new-password" name="refuel_auth_code" type="password" required>
<span class="form-control-feedback glyphicon" id="iconBad8"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="submit" class="btn btn-success">Add Fuel</button>
</div>
</form>
</div>
</div>
</div>
JSFiddle Demo
The problem is here:
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
Your div has id="fuel" and so does the input. Remove the id from the div or make it unique. Also, there is no name attribute for div elements, you should remove that as well.
how can i take the parameter(number) on a bootstrap input element when i click on the button??
<form>
<div class="form-group">
<div class ="col-md-6 input-group">
<span class="input-group-addon">Larghezza</span>
<div id="myNumber"> <input type="number" class="form-control" id="focusedInput" placeholder="Inserisci qui..." > </div>
</div>
</div>
</form>
<button type="button" onclick="myFunction()" class="btn btn-default">Calcola</button>
my js code... Then i use the number for some math operation
function myFunction() {
var x = document.getElementById("myNumber").value;
You are reading value property of div element while it is a property of the input.
Use id of input and it will work.
function myFunction() {
var x = document.getElementById("focusedInput").value;
console.log(x);
}
<form>
<div class="form-group">
<div class ="col-md-6 input-group">
<span class="input-group-addon">Larghezza</span>
<div id="myNumber">
<input type="number" class="form-control" id="focusedInput" placeholder="Inserisci qui..." >
</div>
</div>
</div>
</form>
<button type="button" onclick="myFunction()" class="btn btn-default">Calcola</button>
var x = document.getElementById("focusedInput").value;
You need to reference the input element, not its container.
I would like to create dynamically some input fields, that I used ng-repeat with ng-model. I meet some problems. ng-model without ng-repeat works correctly (transitPointStart). transits should work exactly the same, but they don't. What am I missing?
(link to plunker on the bottom)
transitPointStart:
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="field_start">Start Point</label>
<input type="text" class="form-control" name="field_start" id="field_start"
ng-model="transitPointStart.city" placeholder="e.g. London"
/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="field_start_date">Date</label>
<div class="input-group">
<input id="field_start_date" type="text" class="form-control" placeholder="YYYY-MM-DD HH:MM"
name="field_start_date"
datetime-picker="{{dateformat}}" ng-model="transitPointStart.date"
is-open="datePickerOpenStatus.field_start_date"
/>
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="openCalendar('field_start_date')"><i
class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</div>
</div>
transits:
<div class="row" ng-repeat="transit in transits">
<!--TEST-->
<!--<div> Model: {{transit.modelName}} </div>-->
<!--<div> dateModel: {{transit.dateModelName}} </div>-->
<!--<div> datePicker: {{transit.datePickerName}} </div>-->
<!--<div> fieldName: {{transit.fieldName}} </div>-->
<!--<div> fieldDateName: {{transit.fieldDateName}} </div>-->
<!--<div> button: {{transit.buttonDateName}} </div>-->
<!--/TEST-->
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="transit.fieldName">Transit {{$index+1}}</label>
<input type="text" class="form-control" name="transit.fieldName" id="transit.fieldName"
ng-model="transit.modelName" placeholder="transit"
/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="transit.fieldDateName">Date {{$index+1}}</label>
<div class="input-group">
<input id="transit.fieldDateName" type="text" class="form-control" placeholder="e.g"
name="transit.fieldDateName"
datetime-picker="{{dateformat}}" ng-model="transit.dateModelName"
is-open="transit.datePickerName"
/>
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="transit.buttonDateName"><i
class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-2">
<span class="btn btn-primary" ng-click="addTransit()" ng-if="transits.length < 3">Add transit</span>
</div>
<div class="col-lg-2"></div>
</div>
controller:
$scope.transits = [];
$scope.addTransit = function () {
var tempId = $scope.transits.length + 1;
var tempName = "transitPoint_" + tempId;
var tempModelName = tempName + ".city"; // Here I would like to have access to transitPoint.city
var tempDateName = tempName + ".date"; // as above (transitPoint.date)
var tempDate = "datePickerOpenStatus.field_transit_date_" + tempId;
var tempFieldName = "field_transit_" + tempId;
var tempFieldDateName = "field_transit_date_" + tempId;
var tempButton = "openCalendar('" + tempFieldDateName + "')";
$scope.transits.push({
modelName: tempModelName,
dateModelName: tempDateName,
datePickerName: tempDate,
fieldName: tempFieldName,
fieldDateName: tempFieldDateName,
buttonDateName: tempButton
});
}
/*
{...} - rest of code, sending queries (vm.save() ect.)
*/
$scope.datePickerOpenStatus = {};
$scope.datePickerOpenStatus.field_start_date = false;
$scope.datePickerOpenStatus.field_end_date = false;
// I should've used loop here
$scope.datePickerOpenStatus.field_transit_date_1 = false;
$scope.datePickerOpenStatus.field_transit_date_2 = false;
$scope.datePickerOpenStatus.field_transit_date_3 = false;
$scope.openCalendar = function (date) {
$scope.datePickerOpenStatus[date] = true;
};
Demo: Plunker
Some of the bindings in your HTML are not correct. You need to use interpolation (the {{ }} format) whenever you need to emit data from the model into the HTML.
For example, when assigning IDs, you have:
<input id="transit.fieldDateName" type="text" class="form-control" placeholder="e.g" name="transit.fieldDateName" ...
This should be:
<input id="{{transit.fieldDateName}}" type="text" class="form-control" placeholder="e.g" name="{{transit.fieldDateName}}" ...
Second, your ng-click syntax is not correct. You should not create the openCalendar expression in JavaScript, but in your HTML, like so:
<button type="button" class="btn btn-default" ng-click="openCalendar(transit.fieldDateName)">
I think your Plnkr is missing some scripts and/or steps to make the calendar work, but these changes will at least cause your openCalendar function to get called.
i have a field with 'add' and 'remove' field options and my problem is if someone click remove button at first time then there is nothing left. however i created a another button and hide it by this code.
$('#more_fields').hide();
is that possible to show this button when there is no field or no button with deleteMe class available
i'm using this code for delete fields.
$(document).on("click",".deleteMe", function(){
$(this).closest(".addform").remove();
});
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="addform"><div class="input-group"> <label for="Services">Services '+room+'</label> <input type="text" class="form-control" id="Services" name="serve[]" style="max-width: 148px;" placeholder="Add Services"> <span class="input-group-btn" > <button class="btn deleteMe" style="">×</button> <button class="btn btn-success pull-right" onclick="add_fields();" type="button"><i class="fa fa-plus"></i></button> </span> </div></div>';
objTo.appendChild(divtest)
}
//]]>
$(document).on("click",".deleteMe", function(){
$(this).closest(".addform").remove();
});
$('#more_fields').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="form-inline">
<div class="">
<div class="form-group">
<div id="room_fileds" class="text-center">
<div class="addform">
<!--<label for="qualification">Services 1</label>
<input type="text" class="form-control" id="Service" style="" placeholder="Add Services">
-->
<div class="input-group">
<label for="Services">Services 1</label>
<input type="text" class="form-control" id='Services' name="serve[]" style="max-width: 148px;" placeholder="Add Services">
<span class="input-group-btn" >
<button class="btn deleteMe" style="">×</button>
<button class="btn btn-success pull-right" onclick="add_fields();" type="button"><i class="fa fa-plus"></i></button>
</span>
</div>
<span id="err_quali" style="color:red;display:none;font-size:13px;padding-left:105px;">Enter only Chars</span>
</div>
</div>
<input type="button" class="btn btn-success btn-sm" id="more_fields" onclick="add_fields();" value="Add Services" />
</div>
</div>
</form>
on delete do like
room -= 1;
than if at some point you do
if(room===0) { /*here show your button */ }
I've noticed that you use ID for buttons like #err_quali, #Services... Don't. you're going to have load of duplicate IDs on the page which is wrong. Use classes instead.
jsBin demo
var rooms = 1;
var c = 1;
var $roomsWrapper = $("#room_fileds"); // the parent
var $room = $(".input-group").clone(); // Store a group
$('#more_fields').hide();
$(".form-inline").on("click", ".deleteMe", function(ev) {
ev.preventDefault();
rooms -= 1;
$(this).closest(".input-group").fadeOut(300, function(){
$(this).remove();
});
$('#more_fields').toggle( !rooms );
}).on("click", ".addField, #more_fields", function(ev) {
ev.preventDefault();
rooms += 1;
c += 1;
var $klon = $room.clone();
$klon.find(".groupNum").text(c);
$roomsWrapper.append( $klon );
});
.err_quali{
color:red;
display:none;
font-size:13px;
padding-left:105px;
}
.form-control{
max-width: 148px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- FORM -->
<form class="form-inline">
<div id="room_fileds">
<!-- CLONABLE FIELD HELPER -->
<div class="input-group">
<label for="Services">Services <span class="groupNum">1</span></label>
<input type="text" name="serve[]" placeholder="Add Service">
<span class="err_quali">Enter only Chars</span>
<span class="input-group-btn" >
<button class="deleteMe btn">×</button>
<button class="addField btn" type="button">+</button>
</span>
</div>
<!-- Here jQuery appends Room group clones -->
</div>
<button id="more_fields">Add Services</button>
</form>