Only the first element (the first button) will get the remove event from the class "remove-row"
My HTML:
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
My JavaScript/jQuery:
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$(this).parent().remove();
});
});
I hope it's not duplicated because I tried this and some other questions, but without success.
$(document).ready(function () {
$('.remove-row').each(function(index) {
$(this).on('click', function () {
$(this).parent().remove();
});
});
});
Would do it, see this Plunk. Note that you have to click exactly on the (line of the) X to make it work.
$(function () {
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$(this).parent().remove();
});
});
$('.draggable-button').mousedown(function (e) {
if (e.which === 1) {
var button = $(this);
var button_id = button.attr('id');
var parent_height = button.parent().innerHeight();
var top = parseInt(button.css('top'));
var original_ypos = button.position().top; //original ypos
var drag_min_ypos = 0 - original_ypos;
var drag_max_ypos = parent_height - original_ypos - button.outerHeight();
var drag_start_ypos = e.clientY;
var my_ypos = original_ypos;
//Set current order for all
$('.draggable-button').each(function (i) {
$(this).attr('data-order', (i + 1));
});
var prev_button = button.prev('.draggable-button');
var next_button = button.next('.draggable-button');
var prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
var next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
$(window).on('mousemove', function (e) {
//Move and constrain
button.addClass('drag');
var direction = my_ypos > button.position().top ? 'up' : 'down';
var new_top = top + (e.clientY - drag_start_ypos);
my_ypos = button.position().top;
button.css({top: new_top + 'px'});
if (new_top < drag_min_ypos) {
button.css({top: drag_min_ypos + 'px'});
}
if (new_top > drag_max_ypos) {
button.css({top: drag_max_ypos + 'px'});
}
//Check position over others
if (direction == 'down' && next_button_ypos != '') {
if (my_ypos > next_button_ypos) { //crossed next button
next_button.css({top: (parseInt(next_button.css('top')) - next_button.outerHeight(true)) + 'px'}); //up once
var tmp_order = next_button.attr('data-order');
next_button.attr('data-order', button.attr('data-order')); //switch order
button.attr('data-order', tmp_order);
prev_button = next_button;
next_button = next_button.nextAll('.draggable-button:not(.drag)').first();
prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
}
} else if (direction == 'up' && prev_button_ypos != '') {
if (my_ypos < prev_button_ypos) { //crossed prev button
prev_button.css({top: (parseInt(prev_button.css('top')) + prev_button.outerHeight(true)) + 'px'}); //down once
var tmp_order = prev_button.attr('data-order');
prev_button.attr('data-order', button.attr('data-order')); //switch order
button.attr('data-order', tmp_order);
next_button = prev_button;
prev_button = prev_button.prevAll('.draggable-button:not(.drag)').first();
prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
}
}
});
$(window).on('mouseup', function (e) {
if (e.which === 1) {
$('.draggable-button').removeClass('drag');
$(window).off('mouseup mousemove');
//Reorder and reposition all
$('.draggable-button').each(function () {
var this_order = parseInt($(this).attr('data-order'));
var prev_order = $(this).siblings('.draggable-button[data-order="' + (this_order - 1) + '"]');
if (prev_order.length > 0) {
$(this).insertAfter(prev_order);
}
});
$('.draggable-button').css('top', '0');
$('.draggable-button').removeAttr('data-order'); //reset
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
The problem wasn't in the code I posted. I forgot to mention that I made the buttons draggable. For that, I use a plugin, which prevented the click in some way.
Now debugging and trying to fix it, thanks for the help!
Please use it like this:
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$('.remove-row').parent().remove();
});
});
Related
As it stands right now, my click and drag functionality can be used anywhere on the document when it is enabled. But I want to have it so that a user can only click and drag to highlight within the image element on my page so that the coordinates returned can be used without worry. I thought limiting it to within its own div element along with only the image would work but it is still enabled anywhere on the page. Changing the location of the div element doesn't really do anything.
Here is my code:
var enabled = false;
let canvasElem = document.querySelector("body");
function getCursorPosition(e) {
e = e || window.event;
if (e) {
if (e.pageX || e.pageX == 0) return [e.pageX, e.pageY];
var dE = document.documentElement || {};
var dB = document.body || {};
if ((e.clientX || e.clientX == 0) && ((dB.scrollLeft || dB.scrollLeft == 0) || (dE.clientLeft || dE.clientLeft == 0)))
return [e.clientX + (dE.scrollLeft || dB.scrollLeft || 0) - (dE.clientLeft || 0), e.clientY + (dE.scrollTop || dB.scrollTop || 0) - (dE.clientTop || 0)];
}
return null;
}
function buttonClick() {
setTimeout(function() {
enabled = true;
console.log(enabled)
startWorking();
}, 1000);
}
function mousedown(e) {
getMousePosition(canvasElem, e);
var mxy = getCursorPosition(e);
var box = document.getElementById("selection_box");
box.orig_x = mxy[0];
box.orig_y = mxy[1];
box.style.left = mxy[0] + "px";
box.style.top = mxy[1] + "px";
box.style.display = "block";
document.onmousemove = mousemove;
document.onmouseup = mouseup;
}
function mousemove(e) {
var mxy = getCursorPosition(e);
var box = document.getElementById("selection_box");
box.style.width = (mxy[0] - box.orig_x) + "px";
box.style.height = (mxy[1] - box.orig_y) + "px";
}
function mouseup(e) {
var mxy = getCursorPosition(e),
box = document.getElementById("selection_box"),
image_box = document.getElementById("image_box"),
selection = getSelection;
box.style.display = "none";
box.style.width = "0";
box.style.height = "0";
document.onmousemove = function() {};
document.onmouseup = function() {};
getMousePosition(canvasElem, e);
stopWorking();
console.log(enabled);
}
function startWorking() {
if (enabled) {
document.onmousedown = mousedown;
}
}
function stopWorking() {
if (enabled) {
enabled = false;
document.onmousedown = null;
}
}
function getMousePosition(canvas, event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
console.log("Coordinate x: " + x,
"Coordinate y: " + y);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="sideform">
<h1>Custom App</h1>
<h2>Doc Type: (Single/Multi)</h2>
<h2>Extract Type:</h2>
<br>
<form action="">
<!--TOGGLE VISIBILITY FOR...-->
<!--ANGLE-->
<label class="switch">
<input type="checkbox">
<span class="slider-angle"></span>
</label>
<br>
<br>
<!--LINES-->
<label class="switch">
<input type="checkbox">
<span class="slider-lines"></span>
</label>
<br>
<br>
<!--TEXT-->
<label class="switch">
<input type="checkbox">
<span class="slider-text"></span>
</label>
<!--SPECIFY TABULAR EXTRACTION FOR...-->
<!--LATTICE TABLES-->
<h3>Lattice Tables</h4>
<label for="table2">Table:</label>
<button type="button" class="button" id="table2" name="table2" onclick="buttonClick()">Table Outline</button>
<br>
<label for="header2">Header:</label>
<button type="button" class="button" id="header2" name="header2" onclick="buttonClick()">Header Outline</button>
<br>
<label for="rel2">Relevant Lines:</label>
<button type="button" class="button" id="rel2" name="rel2" onclick="buttonClick()">Relevant Lines</button>
<br>
<label for="ignore2">Lines to Ignore:</label>
<button type="button" class="button" id="ignore2" name="ignore2" onclick="buttonClick()">Ignore Lines</button>
<!--STREAM TABLES-->
<h3>Stream Tables</h4>
<label for="table1">Table:</label>
<button type="button" class="button" id="table1" name="table1" onclick="buttonClick()">Table Outline</button>
<br>
<label for="header1">Header:</label>
<button type="button" class="button" id="header1" name="header1" onclick="buttonClick()">Header Outline</button>
<br>
<label for="rel1">Relevant Lines:</label>
<button type="button" class="button" id="rel1" name="rel1" onclick="buttonClick()">Relevant Lines</button>
<h2>Clustering Type:(X/Y/None)</h2>
<label for="conversion"></label>
<button type="submit" id="conversion" name="conversion" class="button">Perform Conversion</button>
</form>
</div>
<div class="main">
<h1 class="title">(FILE NAME)</h1>
</div>
<div class="temp">
<img src="styles/sample.png" alt="sample.png">
<div id="selection_box"></div>
</div>
If adding my css elements to this would be helpful just let me know and I'll make an edit to add them.
jQuery previous button not working as expected.
Basically the best way to explain it is if I'm on question 5 and I click the previous button, it defaults to question 1 rather than going to question 4.
So it's defaulting to question 1... That's a problem.
What to do?
jQuery is in the bottom in script tags.
if (i.Question_Type == "DROPDOWN")
{
<div class="container text-center">
<div class="row idrow" data-questions="#counter">
#{
counter++;
}
<div id="question1" class="form-group">
<label class="lab text-center" for="form-group-select">
#i.Question_Order #Html.Raw(#i.Question)
</label>
<select class="form-control" id="form-group-select">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<option> #i.qOps.options[t]</option>
}
else
{
<option> #x</option>
}
}
</select>
</div>
</div>
</div>
}
if (i.Question_Type == "RADIO")
{
<div class="container">
<div class="row idrow" data-questions="#counter">
#{counter++;
}
<div class="form-group">
<label class="lab" for="questions">
#i.Question_Order #i.Question
</label>
<div class="row">
<div class="col-xs-12">
<div id="question1" class="radio-inline">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<label class="radio-inline"><input type="radio" name="question"> #i.qOps.options[t]</label>
}
else
{
<label class="radio-inline"><input type="radio" min="0" max="#x" name="question"></label>
}
}
</div>
</div>
</div>
</div>
</div>
</div>
}
if (i.Question_Type == "CHECKBOX")
{
for (int y = 1; y <= Convert.ToInt32(i.Question_SubType); y++)
{
#*<div class="container">
<div class="row">
<label>#y</label> <input type="checkbox" name="question">
</div>
</div>*#
}
}
}
<div class="azibsButtons">
<button type="button" id="previous" class="btn btn-primary pull-left">Prev</button>
<button type="button" id="next" class="btn btn-primary pull-right">Next</button>
</div>
<script>
$(document).ready(function () {
$(".idrow").each(function (i) {
var inner = $(this).data('questions');
if (inner == 0) {
$(this).removeClass('hidden');
} else {
$(this).addClass('hidden');
}
});
$("#next").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal++;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
$("#previous").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal--;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
});
});
</script>
Hey guys I got the solution Thanks to Daniel.
The next event closing braces were wrapped around the previous event, which caused the problem to default to question 1 when clicked previous.
$("#next").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal++;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
$("#previous").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal--;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
I am new to javascript and need help with implementing the following function: when the user enters a zipcode, any other entries of the form are erased and the zip code is used to look up an address.
How would I do that? The following is code I am using to get location for near by urgentcare areas:
(
function(){
var $scope, $location;
var urgentCareApp = angular.module('urgentCareApp',['ui.bootstrap']);
urgentCareApp.controller('UrgentCareController',function($scope,$http,$location,anchorSmoothScroll){
$scope.Lang = 'initVal';
$scope.ShowResults = false;
$scope.ShowDesc = true;
$scope.NoResults = false;
$scope.currentPage = 1;
$scope.maxPageNumbersToShow = 10;
$scope.formModel = {};
$scope.searchMode = 0;
$scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
$scope.searchParam = {};
$scope.searchParam.Distance = $scope.miles[0];
console.log($scope.searchParam.Distance);
//$scope.searchParam.Specialty = $scope.Specialties[0];
$scope.GetCurrentZip = function (){
try{
var lon, lat;
console.log('starting geoposition code.');
if("geolocation" in navigator){
window.navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude.toFixed(3);
lon = pos.coords.longitude.toFixed(3);
console.log(lat + ' ' + lon);
$http.get("/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
.success(function(response){
console.log('Response: ' + response);
$scope.searchParam.Zip = response;
console.log('object set');
})
})
}
else{ console.log('No geolocation'); }
}
catch(err) { console.log(err.message); }
}
$scope.GetCityList = function (){
try{
$http.get("/remote/ReturnUrgentCareCityList.cfm")
.success(function(response){
$scope.Cities = response.Cities;
})
}
catch(err){}
}
$scope.SearchUrgentCare = function(searchParam){
try{
$scope.searchMode = 1;
var queryString='';
if($scope.formModel && $scope.formModel !== searchParam){
$scope.resultsCount = 0;
currentPage = 1;
}
if(searchParam){
$scope.formModel = searchParam;
for(var param in searchParam){
console.log(param + ' ' + searchParam.hasOwnProperty(param) + ' ' + searchParam[param]);
if(searchParam.hasOwnProperty(param)){
var paramValue = searchParam[param].value ? searchParam[param].value.trim() : searchParam[param].trim();
if (paramValue.length > 0)
queryString += param + '=' + paramValue + '&';
}
}
}
console.log(queryString);
queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;
$http.get("/remote/ReturnUrgentCareList.cfm" + queryString)
.success(function(response){
$scope.urgentCareCenters = response.UrgentCareCenters;
$scope.resultsCount = response.rowCount;
if (!$scope.urgentCareCenters){
$scope.NoResults = true;
$scope.ShowResults = false;
$scope.ShowDesc = false;
}
else{
$scope.NoResults = false;
$scope.ShowResults = true;
$scope.ShowDesc = false;
}
})
}
catch(err){ alert('No response.: ' + err.message); }
}
$scope.$watchGroup(['currentPage'], function(){
try{
if($scope.searchMode == 1){
$scope.SearchUrgentCare($scope.formModel);
}
}
catch(err){}
});
$scope.GetCityList();
$scope.GetCurrentZip();
$scope.gotoElement = function (eID){
var browserWidth = screen.availWidth;
if (browserWidth < 768)
anchorSmoothScroll.scrollTo(eID);
};
});
urgentCareApp.service('anchorSmoothScroll', function(){
this.scrollTo = function(eID) {
// This scrolling function
// is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};
});
urgentCareApp.directive('allowPattern',[allowPatternDirective]);
function allowPatternDirective(){
return{
restrict: "A",
compile: function(tElement, tAttrs){
return function(scope, element, attrs){
element.bind("keypress", function(event){
var keyCode = event.which || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){
event.preventDefault();
return false;
}
});
}
}
}
}
urgentCareApp.filter('PhoneNumber', function(){
return function(phoneNumber){
var dash = '-';
if(phoneNumber){
var pn = phoneNumber;
pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
pn = [pn.slice(0, 3), dash, pn.slice(3)].join('');
return pn;
}
return phoneNumber;
}
});
})();
The Form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate="" role="form">
<div class="form-group"><input class="form-control" id="urgentcare" ng-model="searchParam.UrgentCareName" placeholder="Urgent Care Name" type="text" /></div>
<div class="form-group"><select class="form-control" id="city" ng-model="searchParam.City" ng-options="City.value for City in Cities"><option disabled="disabled" selected="selected" value="">City</option> </select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group"><select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
</div>
Not sure about what you're trying to do, but for sure you can use ngChange directive, so when the user types anything to Zip you can do what you want in your controller.
See this demo:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope, $http) {
$scope.reset = function() {
// If you just want to clear the fields do it:
var zip = angular.copy($scope.searchParam.Zip);
$scope.searchParam = {};
$scope.searchParam.Zip = zip;
}
});
})();
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate="" role="form">
<div class="form-group">
<input class="form-control" id="urgentcare" ng-model="searchParam.UrgentCareName" placeholder="Urgent Care Name" type="text" />
</div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City" ng-options="City.value for City in Cities">
<option disabled="disabled" selected="selected" value="">City</option>
</select>
</div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding">
<div class="form-group">
<input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" ng-change="reset()" type="text" />
</div>
</div>
</div>
<div class="form-group">
<input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" />
</div>
</form>
</div>
</div>
</body>
</html>
you should either use angular $scope.$watch or ng-change directive
for example if i want do to something when the variable $scope.varA changes
you can use:
$scope.$watch("varA", function(){
//my code
//in your case (type searchParams.Zip where i wrote varA)
var zip = $scope.searchParams.Zip; //keep before cleaning
$scope.searchParams = {};
$scope.searchParams.Zip = zip;
});
or declare a angular function and use ng-change directive on the html input where you used ng-model for the zip code, (add this as attribute: ng-change="clean_form();")
$scope.clean_form = function(){
var zip = $scope.searchParams.Zip;
$scope.searchParams = {};
$scope.searchParams.Zip = zip;
};
the form cleaning code comes from developer033, i just wanted to show you how you could cause that code to happen
I have a form field calls 'No of Partners' that depends and appear on the selection of the previous dropdown . else it is hidden . with the class 'hide'.My problem I am not able to append a class has-success after validation of this feild. The Code is as follows:
<div class="row" id="divtypeofb">
<div class="col-xs-12">
<div class ="col-md-6">
<div class="form-group">
<label><li class="hide"></li>No of partners<span style="color: red;"> *</span></label>
<input type="number" name="no_of_promoters" id="number_of_promoters" min="2" value="<?=$business_info_details['no_of_promoters'];?>" class="form-control" placeholder="No of Partners involved" onkeyup="numberValidation('no_of_promoters')" >
<span class="help-block hide"><li class="hide"></li>Select the number of partners involved.</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#company_type_id').change(function(){
if($('#company_type_id').val()!=1){
$("#divtypeofb").show(1000).removeClass("hide");
} else {
$("#divtypeofb").hide(1000).addClass("hide");
$("#no_of_promoters").val('');
}
});
});
function numberValidation(id){
if($("#" + id).val() == null || $.trim($("#" + id).val()) == "" || !$.isNumeric($("#" + id).val())){
var div = $("#" +id).closest('div');
var label = div.find('label');
var span = div.find('span');
div.removeClass("has-success");
div.addClass("has-error");
label.find('li').removeClass('fa fa-check hide');
label.find('li').addClass('fa fa-times-circle-o');
span.removeClass("hide");
$("#" + id).focus();
//$("#" + id).scrollTo($(this),1000);
return false;
} else{
var div = $("#" +id).closest('div');
var label = div.find('label');
var span = div.find('span');
div.removeClass("has-error");
div.addClass("has-success");
label.find('li').removeClass('fa fa-times-circle-o hide');
label.find('li').addClass('fa fa-check');
span.addClass("hide");
return true;
}
}
</script>
The keyup attribute is calling the validator with the wrong id: numberValidation('no_of_promoters'). The name of the element is no_of_promoters but the id is number_of_promoters:
<input type="number" name="no_of_promoters" id="number_of_promoters" ...
Your code could also use a clean up since it contains duplicate code in the if and else.
<div class="row" id="divtypeofb">
<div class="col-xs-12">
<div class ="col-md-6">
<div class="form-group">
<label><li class="hide"></li>No of partners<span style="color: red;"> *</span></label>
<input type="number" name="no_of_promoters" id="number_of_promoters" min="2" value="<?=$business_info_details['no_of_promoters'];?>" class="form-control" placeholder="No of Partners involved" onkeyup="numberValidation('number_of_promoters')" >
<span class="help-block hide"><li class="hide"></li>Select the number of partners involved.</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#company_type_id').change(function(){
if($('#company_type_id').val()!=1){
$("#divtypeofb").show(1000).removeClass("hide");
} else {
$("#divtypeofb").hide(1000).addClass("hide");
$("#number_of_promoters").val('');
}
});
});
function numberValidation(id){
var input = $("#" + id);
var value = input.val();
var div = input.closest('div');
var label = div.find('label');
var span = div.find('span');
var li = label.find('li');
if(value == null || $.trim(value) == "" || !$.isNumeric(value)){
div.removeClass("has-success")
.addClass("has-error");
li.removeClass('fa fa-check hide')
.addClass('fa fa-times-circle-o');
span.removeClass("hide");
input.focus();
//input.scrollTo($(this),1000);
return false;
} else{
div.removeClass("has-error")
.addClass("has-success");
li.removeClass('fa fa-times-circle-o hide')
.addClass('fa fa-check');
span.addClass("hide");
return true;
}
}
</script>
I have created a stand alone code for enabling/disabling input field and it is working perfectly .
HTML:
Identification Type:
<select name="Identification-Type" id="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="23434">--sfgdg--</option>
<option value="135111">--dfgb--</option>
<option value="1165611">--gdg--</option>
<option value="114511">--vcbc--</option>
</select>
<!-- <input type="checkbox" class="Identification-Number" value="Identification-Number"
name="Identification-number" id="Identification-Number"> -->
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number" id="Identification-Number">
JS:
$('select[name="Identification-Type"]').change(function () {
var $this = $('#Identification-Number');
$this.attr("disabled", false);
$this.attr("disabled", ($(this).val() == '1111') ? true : false);
}).trigger('change');
JSFIDDLE LINK
But,when I tried to incorporate this logic in another form, it is not working .
HTML:
<form name="pancettaForm" method="post" action="demor" id="pancettaForm">
<ul>
<li>
<label for="PartyChoose">Choose Appropriate Party:</label>
</li>
<br>
<input id="person" name="PartyChoose" type="radio" value="update-person" class="required" />Person
<br />
<input id="organization" name="PartyChoose" type="radio" value="update-organization" class="required" />Organization
<br />
<li id="Family-Name" style="display: none;">
<input type="checkbox" class="Family-Name" value="Family-name" name="Family-name">
<label for="Family-Name"><em>*</em>Family Name:</label>
<input type="text" name="Family-Name" class="required">
</li>
<li id="Organization-Name" style="display: none;">
<inpname="Organization-name">
<label for="Organization-Name"><em>*</em>Organization Name:</label>
<input type="text" name="Organization-Name" class="required">
</li>
<div class="extraPersonTemplate">
<div class="controls-row">
<li id="Identification-Type" style="display: none;">Identification Type:
<select name="Identification-Type" class="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="1">--sdsd--</option>
<option value="2">--cxc--</option>
<option value="3">--cvcv--</option>
<select> <a id="Identification-Number" style="display: none;">
<input type="hidden" class="Identification-Number">
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number">
</a>
</li>
</div>
</div>
<div id="container"></div>
<a href="#" id="addRow" style="display: none;"><i class="icon-plus-sign icon-white">
</i> Add Identifier</a>
<li id="Adminsys-Type" style="display: none;">Admin System Type:
<select name="Adminsys-Type" class="Adminsys-Type">
<label for="Adminsys-Type">Admin Type:</label>
<option value="0">--Select--</option>
</select>
</li>
<li id="Adminsys-Number" style="display: none;">
<input type="checkbox" class="Adminsys-Number" value="Adminsys-Number" name="Adminsys-number">
<label for="Adminsys-Number"><em>*</em>Admin System Value:</label>
<input type="text" name=Adminsys-Number>
</li>
</ul>
<input type="submit" id="button" name="submit" value="Search">
</form>
JS:
$(document).ready(function () {
var counter = 0;
$('input[name=Organization-Name]').attr('disabled', true);
$('input[name=Identification-Number]').attr('disabled', true);
$('input[name=Family-Name]').attr('disabled', true);
$('input[name=Adminsys-Number]').attr('disabled', true);
$('#pancettaForm').change(function () {
$('.Organization-Name').click(function () {
if ($('.Organization-Name').is(':checked')) {
$('input[name=Organization-Name]').val('').attr('disabled', false);
} else {
$('input[name=Organization-Name]').attr('disabled', true);
}
});
$('select[name="Identification-Type' + counter + '"]').change(function () {
var $this = $('.Identification-Number');
var $input = $this.siblings('input[type=text]');
$input.attr("disabled", false);
$input.attr("disabled", ($(this).val() == '1111') ? true : false);
});
$('.Adminsys-Number').click(function () {
if ($('.Adminsys-Number').is(':checked')) {
$('input[name=Adminsys-Number]').val('').attr('disabled', false);
} else {
$('input[name=Adminsys-Number]').attr('disabled', true);
}
});
$('.Family-Name').click(function () {
if ($('.Family-Name').is(':checked')) {
$('input[name=Family-Name]').val('').attr('disabled', false);
} else {
$('input[name=Family-Name]').attr('disabled', true);
}
});
$('#Family-Name,#Identification-Number,#Organization-Name').hide();
if ($('#person').prop('checked')) {
$('#Family-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
} else if ($('#organization').prop('checked')) {
$('#Organization-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
}
});
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
$('<div/>', {
'class': 'extraPerson' + counter,
'id': 'extraPerson' + counter,
html: GetHtml() + '</i> Remove Identifier'
}).hide().appendTo('#container').slideDown('slow');
counter++;
});
$("#container").on('click', '.removeRow', function () {
//$("#extraPerson"+counter).remove();
if (counter < 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$(this).parent().remove();
});
function GetHtml() {
// var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
if (counter == 0) {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
counter++;
return $html.html();
} else {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
// $html.find('[id=Identification-Type]')[0].id="Identification-Type" + counter;
// var remove='</i> Remove Identifier';
return $html.html();
}
}
})
JSFIDDLE LINK
How can I dynamically change the name of select attribute so that I can selectively enable and disable input fields in multiple rows.
Hope this will help you a bit and I hope I got it correct:
I reworked you change function which determines the select boxes and enables the input field, like this
$('.Identification-Type').change(function () {
//#Identification-Type input
/** this can be used to count the input fields and use it in a loop later **/
var $inputFields = $('.extraPersonTemplate #Identification-Type input').length;
var $idNumber = $('input[name=Identification-Number]');
var $idNumber0 = $('input[name=Identification-Number0]');
($('select[name=Identification-Type]').val() == '1111') ? $idNumber.attr('disabled', true) : $idNumber.removeAttr('disabled');
($('select[name=Identification-Type0]').val() == '1111') ? $idNumber0.attr('disabled', true) : $idNumber0.removeAttr('disabled')
})
But from my point of view, this is not a the best approach since its not very dynamically.
If you manage to count up the select[name=Identification-Type] + counter not only for one input but for both of them like <input type="text" name="Identification-Number0"> and <input type="text" name="Identification-Number1"> it would be possible to include a loop within in this change function and loop over the $inputFields which are found
http://jsfiddle.net/xKL44/2/ this has helped me in the past... Try it out!
$('#wow').change(function() {
// Remove any previously set values
$('#show_box, #total_box').empty();
var sum = 0,
price;
$(this).find('option:selected').each(function() {
// Check that the attribute exist, so that any unset values won't bother
if ($(this).attr('data-price')) {
price = $(this).data('price');
sum += price;
$('#show_box').append('<h6>' + price + '</h6>');
}
});
$('#total_box').text(sum);
});