Change button text based on radio button option using angular - javascript

I created an angular application that has a 2 radio controls and a text button. I would like to change the text of the button under 2 separate conditions.
1. Changing the radio button will change it to either 'Upgrade' or 'Save'
2. When the text button is clicked the button is disabled and text changed to 'Processing'.
This is the html:
<div class="row" style="margin-top: 5px; margin-bottom: 5px;">
<input type="radio" ng-model="outputType" value="Database">
<label>Database</label>
</div>
<div class="row" style="margin-top: 10px; margin-bottom: 10px;">
<input type="radio" ng-model="outputType" value="File">
<label>Xml File</label>
</div>
<div>
<button id="upgradeDBButton" type="button" ng-click="UpgradeDatabase()"
ng-disabled="upgradeBtndisabled" class="btn btn-info"
style="float: right; margin-right: 5px;">{{upgradeBtnText}}</button>
</div>
This is the javascript
angular.module('vow-administration-ui')
.controller('UpgradeCtrl', ['$scope', '$modal', 'UpgradeDB', 'CreateXmlFile', 'TestConnection',
function($scope, $modal, upgradeDB, createXmlFile, testConnection) {
$scope.title = 'Upgrade Database';
$scope.upgradeBtnText = 'Upgrade Database';
$scope.upgradeBtndisabled = false;
};
$scope.UpgradeDatabase = function(){
var currentBtnText = $scope.upgradeBtnText;
$scope.upgradeBtnText = 'Processing...';
$scope.upgradeBtndisabled = true;
upgradeDB.save({ ...
}).$promise.then(function() {
$scope.upgradeBtndisabled = false;
$scope.upgradeBtnText = currentBtnText;
}, function(error){
...
$scope.openMessageModal($scope.messageModalVariables);
$scope.upgradeBtndisabled = false;
$scope.upgradeBtnText = currentBtnText;
})
};
How do I change the button text when the radio buttons are toggled?
Why does by button text not change when the save function is fired?

<div class="row" style="margin-top: 5px; margin-bottom: 5px;">
<input type="radio" ng-model="outputType" value="Database">
<label>Database</label>
</div>
<div class="row" style="margin-top: 10px; margin-bottom: 10px;">
<input type="radio" ng-model="outputType" value="File">
<label>Xml File</label>
</div>
<div>
<button id="upgradeDBButton" type="button" ng-click="UpgradeDatabase()"
ng-disabled="upgradeBtndisabled" class="btn btn-info"
style="float: right; margin-right: 5px;">{{ upgradeBtndisabled ? 'Processing' : ((outputType == 'Database') ? 'Upgrade' : 'File') }}
</button>
</div>
Will do it for you.

You can create $watch, something like
$scope.$watch('outputType', function(newVal){
$scope.upgradeBtnText = newVal === 'Database' ? 'Upgrade' : 'Save';
}

Related

The if/else statement

I want to show a suitable button with if/else statement. For example, when none of the checkboxes are checked I want to display the disabled button, but when one or more checkboxes are checked I want to display another button.
Js
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Html
<input type="checkbox" id="checkAll" style="margin-left:-10px" />
<input type="checkbox" style="margin-left:5px" />
<input type="checkbox" style="margin-left:5px" />
<div class="ml-2">
if(checked){
<button type="button" class="btn btn-danger ">Delete</button>
}else{
<button type="button" class="btn btn-outline-danger" disabled>Delete</button>
}
</div>
As long the button is right next to the other button you don't even need no javascript for that.
Thats of course quite a simple approach and can easily be 'hacked' via the Inspector. But if you do it with Javascript it can be hacked as well.
.checkbox + .button {
opacity: 0.5;
pointer-events: none;
}
.checkbox:checked + .button {
display: none;
}
.checkbox + .button + .button2 {
display: none;
}
.checkbox:checked + .button + .button2 {
display: block;
}
<input type="checkbox" class="checkbox">
<div class="button">Button 1</div>
<div class="button2">Button 2</div>
When none of the checkboxes are checked I want to display the disabled button, but when 1 or more checkbox are checked I want to display another button.
You can include both buttons in the html with one hidden - then in your js show/hide them as appropriate.
A basic implementation would to check:
if ($("input:checkbox:checked").length == 0) {
then use .show() .hide() on each of the buttons as required.
This can be made more streamlined, eg using .toggle($("input:checkbox:checked").length == 0) but this is to show the explicit if/else as requested in the title.
$("#checkAll").change(function() {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
$("input:checkbox").change(function() {
if ($("input:checkbox:checked").length == 0) {
$(".ml-2>.btn-danger").hide();
$(".ml-2>.btn-outline-danger").show();
} else {
$(".ml-2>.btn-outline-danger").hide();
$(".ml-2>.btn-danger").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkAll" />
<input type="checkbox" />
<input type="checkbox" />
<div class="ml-2">
<button type="button" class="btn btn-danger " style='display:none;' >Delete</button>
<button type="button" class="btn btn-outline-danger" disabled>Delete (disabled)</button>
</div>
If - as outlined - you want to have two buttons (rather than, say, one button where you change the classes and properties) you can:
listen for when one of the checkboxes changes
then check the collective state of all the checkboxes
then, depending on that collective state, apply:
Element.classList.add('show')
Element.classList.remove('show')
to show and hide the respective buttons.
Working Example:
// DECLARE VARIABLES
const btnDanger = document.querySelector('.btn-danger');
const btnOutlineDanger = document.querySelector('.btn-outline-danger');
const checkBoxes = document.querySelectorAll('input[type="checkbox"]');
// FUNCTION: REVIEW CHECKBOXES
const reviewCheckBoxes = () => {
let allUnchecked = true;
checkBoxes.forEach((checkBox) => {
if (checkBox.checked) {
allUnchecked = false;
}
});
if (allUnchecked === true) {
btnDanger.classList.remove('show');
btnOutlineDanger.classList.add('show');
}
else if (allUnchecked === false) {
btnDanger.classList.add('show');
btnOutlineDanger.classList.remove('show');
}
}
// ADD EVENT LISTENERS TO EACH OF THE CHECKBOXES
checkBoxes.forEach((checkBox) => {
checkBox.addEventListener('change', reviewCheckBoxes);
});
input[type="checkbox"] {
margin-left: 10px;
}
.btn-danger,
.btn-outline-danger,
input[type="checkbox"]#checkAll {
margin-left: 10px;
}
.btn-danger,
.btn-outline-danger {
display: none;
}
.btn-danger.show,
.btn-outline-danger.show {
display: inline-block;
}
<input type="checkbox" id="checkAll" />
<input type="checkbox" />
<input type="checkbox" />
<button type="button" class="btn btn-danger ">Delete</button>
<button type="button" class="btn btn-outline-danger show" disabled>Delete</button>

Collect list item according to name and store in array or object

I have a dual list in which you get an option to add left list item in right list. And right list is a form. Now i am stuck at a problem where when user click the submit button all the li in right list and there inside values get store in an object with there specific name div id name. I have worked on it for 5 days now but unable to collect data according to div id name. Like
<div id="name1">
<input id="tts" type="text" value="${CTLIST.tts}"> s<br>
<input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
Suppose this is an li of right list.
I want data to get stored like
{
[name : name1,
tts.value : 10,
ifcheckboxcheck : true,
],
[name : name2,
tts.value : 10,
ifcheckboxcheck : true,]
}
HEre is my html
<section class="ctList">
<div class="container">
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"><i class="fa fa-search"
aria-hidden="true" style="padding-right: 20px;"></i></span>
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
</div>
</div>
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
</div>
<ul class="list-group" id="La">
</ul>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left"><i class="fa fa-arrow-left"
aria-hidden="true"></i></span>
</button>
<button class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right"><i class="fa fa-arrow-right"
aria-hidden="true"></i></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
<div class="col-md-10">
<div class="input-group">
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
<span class="input-group-addon glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<form id="rightData" method="POST">
<ul class="list-group" id="accordian">
<!-- right list -->
</ul>
<input type="submit" value="submit" name="submit">
</form>
</div>
</div>
</div>
</div>
</section>
This is my js which is obviously not working
$('.content').hide();
$('.listelement').on('click', function () {
if (!($(this).children('.content').is(':visible'))) {
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
$(function () {
$('body').on('click', '.list-group .list-group-item', function () {
$(this).toggleClass('active');
});
$('.list-arrows button').click(function () {
var $button = $(this), actives = '';
if ($button.hasClass('move-left')) {
actives = $('.list-right ul li.active');
actives.clone().appendTo('.list-left ul');
actives.remove();
} else if ($button.hasClass('move-right')) {
actives = $('.list-left ul li.active');
actives.clone().appendTo('.list-right ul');
actives.remove();
}
});
$('.dual-list .selector').click(function () {
var $checkBox = $(this);
if (!$checkBox.hasClass('selected')) {
$checkBox.addClass('selected').closest('.well').find('ul li:not(.active)').addClass('active right');
$checkBox.children('i').removeClass('glyphicon-unchecked').addClass('glyphicon-check');
} else {
$checkBox.removeClass('selected').closest('.well').find('ul li.active').removeClass('active');
$checkBox.children('i').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
}
});
$('[name="SearchDualList"]').keyup(function (e) {
var code = e.keyCode || e.which;
if (code == '9') return;
if (code == '27') $(this).val(null);
var $rows = $(this).closest('.dual-list').find('.list-group li');
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
});
////printing properties
$(function () {
var ctList = [];
var ctRight = [];
var $tBody = $("#La");
var $rbody = $("#accordian");
$.getJSON('https://api.myjson.com/bins/d6n2a', function (data) {
data.topic_info.qt_ct_connection.map(value => {
value.ct_list.forEach((CTLIST) => {
$tBody.append(`<li class="list-group-item" id="rl">
<span id="nameOfCt">${CTLIST.ct}</span>
View More
<div id="${CTLIST.ct}" class="collapse valueDiv">
<label>${Object.keys(CTLIST)[2]}</label> <input id="tts" type="text" value="${CTLIST.tts}"><br>
<label>${Object.keys(CTLIST)[1]}</label> <input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
</li>`);
});
})
})
})
</script>
<script>
var SendDataObject = {};
$("#rightData").on("submit", function (event) {
event.preventDefault();
var IDs = [];
var list = {};
var data = {} ;
var tts = {};
let rightListLength;
rightListLength = $('#rightData li').length;
var tts = [];
$("#rightData li").each(function (){
$("#rightdata").find("div").each(function(){ IDs.push(this.id);
$('#rightData').find("#tts").each(function () { IDs.push(this.value)})
})
});
// $('#rightData li').each(function () {
// var a = $(this).html();
// console.log("i am writin second", list[$(this).attr('value')] = $(this).html());
// console.log(list[$(this).attr('id')] = $(this).html())
// });
console.log(IDs)
console.log(tts)
CSS
<style>
.ctList {
padding-top: 20px;
}
.ctList .dual-list .list-group {
margin-top: 8px;
}
.ctList .list-left li,
.list-right li {
cursor: pointer;
}
.ctList .list-arrows {
padding-top: 100px;
}
.ctList .list-arrows button {
margin-bottom: 20px;
}
.dual-list.list-left .well li.list-group-item .show {
display: none;
}
</style>
This is rendered HTML in browser if ony one li in right list . ANd if two li then another HTML will be rendered by diffrent i name coming from json and value .
point_in_first_quad
View More
<div id="point_in_first_quad" class="collapse valueDiv">
<label>tts</label> <input id="tts" type="text" value="10"><br>
<label>topic_level</label> <input id="topic_level" type="text" value="capable"><br>
<label>to_be_shown_individually</label> <input id="to_be_shown_individually" type="checkbox" checked=""> <br>
<label>check_for_geometry</label><input id="check_for_geometry" type="checkbox" checked=""><br>
</div>
Adjust your html to include classes or some other identifier, since you cannot have two elements with same ids, things like #topic_level, Probably add a class to help with selection, something like below should help
<div id="point_in_first_quad" class="collapse valueDiv">
<label class="tts-label">tts</label> <input id="tts" class="tts-value" type="text" value="10"><br>...
You added classes to element you want to use in your result.
Adjust the following to make your result object
var finalResult = [];
$('#accordion div').each(function(index, item) {
var $it = $(item);
var ob = {};
ob['name'] = $it.find('.tts-label').text();
ob['tts.value'] = $it.find('.tts-value').val();
ob['ifcheckboxcheck'] = $it.find('[type="checkbox"]').is(":checked");
finalResult.push(ob);
});
Since you have two checkbox field, add a class selector to the one you want to use in result.

Grab data from Dynamic Elements

Attempting to grab data from Dynamic Element before submission of form to calculate duration of time.
As shown in the picture, I have
Day 1 works perfectly, However Day 2 does not calculate the duration of hours. Not sure why that is. Also Unable to edit day 1 once I click to add another day but interested in how to go about fixing the first issue.
var template;
var numOfSegments = 1;
window.addEventListener('load', function() {
template = document.querySelector("#wrapper").innerHTML;
document.querySelector("#more_fields").addEventListener("click", function(e) {
e.preventDefault(); // tell the browser to not send the form
document.getElementById('wrapper').insertAdjacentHTML('beforeend', template); // add next segment
numOfSegments = document.querySelectorAll("div.segment").length;
document.querySelector("div.segment:last-of-type > label").innerHTML = "Day " + (numOfSegments) + ":"; //Updates Segment #
});
})
function deleteMe() {
if (numOfSegments > 1) {
var btn = document.querySelector("#wrapper > div.segment:last-of-type");
btn.remove();
event.preventDefault();
}
}
function addNumSeg() {
var elem = document.getElementById("segments_num");
elem.value = ++numOfSegments;
}
function subtractNumSeg() {
var elem = document.getElementById("segments_num");
if (numOfSegments > 1) {
elem.value = --numOfSegments;
}
}
<div id='segments_num' value=1 >
<form id="seg" oninput="z.value=parseInt(segout.value)-parseInt(segin.value)">
<div id="room_fileds">
<div class="content" id="wrapper">
<div class="segment">
<label id="seg[]" style="margin:0 0 10px 60px;display: inline;">Day 1:</label>
<div class="form-group" style="display: inline;">
<label id=seg-in[] style="margin:0 0 10px 35px;display: inline;">IN:</label>
<input class="form-control seg_in" id="segin" type="text" style="margin:0 0 10px 5px;Width:15%;display: inline;">
</div>
<div class="form-group" style="display: inline;">
<label id=seg-out[] style="margin:0 0 10px 35px;display: inline;">OUT:</label>
<input class="form-control seg_out" id="segout" type="text" style="margin:0 0 10px 5px;Width:15%;display: inline;">
</div>
<div class="form-group" style="display: inline;">
<label id="seg-dur[]" style="margin:0 0 10px 35px;display: inline;">Duration:</label>
<output class="form-control seg_out" form="seg" name="z" for="segin segout" style="margin:0 0 10px 5px;Width:15%;display:inline"; readonly></output>
</div>
</div>
</div>
</div>
</div>
<div style="text-align:right;">
<div style="display:inline;text-align: right;">
<button onclick="deleteMe(); subtractNumSeg();" type="button" style="height: 25px;width:14px;" id="less_fields">-</button>
</div>
<div style="display:inline;text-align: right;">
<button onclick="addNumSeg();" type="button" style="height: 25px;width:14px;" id="more_fields">+</button>
</div>
</div>
<br><br>
<button type="button" class="btn btn-default" id="formSubmit">Submit</button>

Clicking button to Dynamically add a field clears the already existing fields

Creating Dynamic new fields seems to clear the already existing fields
Also not trying to have multiple elements with the same id hence why i don't believe appendChild will work. Perhaps you can find a way to do that while creating different IDs?
Any help welcomed =)
var template;
var a = 1;
window.onload = function() {
template = document.querySelector("#wrapper").innerHTML;
document.querySelector("#more_fields").addEventListener("click", function(e) {
e.preventDefault(); // tell the browser to not send the form
document.getElementById('wrapper').innerHTML += template; // add next segment
document.querySelector("#wrapper > label:last-of-type").innerHTML = "Segment " + (++a) + ":";
});
}
.form-group {
display: inline
}
#wrapper > label {
margin: 0 0 10px 210px;
}
.segment {
display: inline-block;
margin: 0 0 1em
}
.form-group > label {
margin: 0 0 10px 20px;
}
.form-group > input {
width: 15%
}
<div class="container">
<h2>Form</h2>
<form>
<div id="room_fields">
<div class="content" id="wrapper">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
</div>
<br><br>
<div style="text-align: right;">
<button id="more_fields">+</button>
</div>
<br>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
innerHTML will not include the current value entered IIRC but it's still strange that doing += operation will remove the existing value.
However, insertAdjacentHTML() should work as expected.
var template;
var a = 1;
window.onload = function() {
template = document.querySelector("#wrapper").innerHTML;
document.querySelector("#more_fields").addEventListener("click", function(e) {
e.preventDefault(); // tell the browser to not send the form
document.getElementById('wrapper').insertAdjacentHTML('beforeend', template); // add next segment
document.querySelector("#wrapper > label:last-of-type").innerHTML = "Segment " + (++a) + ":";
});
}
.form-group {
display: inline
}
#wrapper > label {
margin: 0 0 10px 210px;
}
.segment {
display: inline-block;
margin: 0 0 1em
}
.form-group > label {
margin: 0 0 10px 20px;
}
.form-group > input {
width: 15%
}
<div class="container">
<h2>Form</h2>
<form>
<div id="room_fields">
<div class="content" id="wrapper">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
</div>
<br><br>
<div style="text-align: right;">
<button id="more_fields">+</button>
</div>
<br>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Basically, my below code is not 100% correct, you should alter it by yourself following mine.
In the HTML, you can define a hidden div which is your wrapper. In its and nested element ids, you can set a pattern like '$$$'.
<div class="content" id="wrapper$$$" sytle="visibility: hidden;">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
In your javascript, declare a global variable named index and replace index value with '$$$'. It will be increased 1 when you add your template dynamically.
template = document.querySelector("#wrapper").innerHTML;
template = template.replace('$$$', index);
index ++;
...
Problem:
The problem here is with using innerHTML, because innerHTML will always override the HTML of your elements so previously typed values will be cleared, that's why you should use .appendChild().
And your logic for dynamic is correct, you just need to chnage the way you add new fields.
Solution:
I tried to rewrite your code so it uses appendChild() in a smart way using the #wrapper innerHTML as template and updating the id dynamically in the new appended fields.
var template = document.querySelector("#wrapper").innerHTML;
function addFields() {
var wrapper = document.createElement("div");
wrapper.innerHTML = template;
wrapper.querySelector("label:last-of-type").innerHTML = "Segment " + (++a) + ":";
document.getElementById('wrapper').appendChild(wrapper);
}
This code will create a new div everytime, wher we put the template HTML inside it, update the label dynamically referring the label inside our current wrapper div using wrapper.querySelector("label:last-of-type"), then finally append this new div to our element.
Demo:
Here's a working Demo snippet:
var template = document.querySelector("#wrapper").innerHTML;
var a = 1;
function addFields() {
var wrapper = document.createElement("div");
wrapper.innerHTML = template;
wrapper.querySelector("label:last-of-type").innerHTML = "Segment " + (++a) + ":";
document.getElementById('wrapper').appendChild(wrapper);
}
window.onload = function() {
document.querySelector("#more_fields").addEventListener("click", function(e) {
e.preventDefault();
addFields();
});
}
<div class="container">
<h2>Form</h2>
<form>
<div id="room_fields">
<div class="content" id="wrapper">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
</div>
<br><br>
<div style="text-align: right;">
<button id="more_fields">+</button>
</div>
<br>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>

Jquery help selecting input fields

I am trying to rewrite this Jquery http://jsfiddle.net/Claudius/gDChA/4/ to use this HTML instead http://pastie.org/2370829
Jquery:
$('button.add', '#companyinfo').live('click', function(e) {
$(this).parent().find('button.remove').show();
$(this).hide();
var element = $(this).parents('.input').find('input').last().clone().prop('value','');
var name = element.prop('name');
var pattern = new RegExp(/\[(.*?)\]/);
var info = name.match(pattern)[1];
var newname = name.replace(pattern, '[' + info + 'info' + ']');
var newid = element.prop('id') + 'info';
element.prop('name', newname);
element.prop('id', newid);
element.insertAfter($(this).parents('.input').find('input').last());
})
$('button.remove', '#companyinfo').live('click', function(e) {
$(this).parent().find('button.add').show();
$(this).hide();
$(this).parents('.input').find('input').last().remove('input');
});
Old HTML
<fieldset id='companyinfo'><legend>Company info</legend>
<div class='input string optional'>
<label for='company_navn' class='string optional'>Count</label>
<input type='text' size='50' name='company[count]' id='company_navn' maxlength="255" class='string optional' />
<div class='button-row'>
<button class='add'>Add info</button>
<button class='remove'>Remove</button>
</div>
</div>
<div class="input string optional">
<label for="company_navn" class="string optional">Navn</label>
<input type="text" size="50" name="company[navn]" maxlength="255" id="company_navn" class="string optional">
<div class='button-row'>
<button class='add'>Add info</button>
<button class='remove'>Remove</button>
</div>
</div>
</fieldset>
New HTML:
<div class="input string optional"><label for="virksomhed_navn" class="string optional"> Navn</label><input type="text" size="50" name="virksomhed[navn]" maxlength="255" id="virksomhed_navn" class="string optional"></div>
<div class="button-row" style="font-size: 11px; width: 110px; float: right; margin-top: -10px; margin-right: 16px;">
<button class="add" style="font-size: 11px;">Add info</button>
<button class="remove" style="font-size: 11px;">Remove</button>
</div>
<div class="input string optional"><label for="virksomhed_name" class="string optional">Name</label><input type="text" size="50" name="virksomhed[name]" maxlength="255" id="virksomhed_name" class="string optional"></div>
<div class="button-row" style="font-size: 11px; width: 110px; float: right; margin-top: -10px; margin-right: 16px;">
<button class="add" style="font-size: 11px;">Add info</button>
<button class="remove" style="font-size: 11px;">Remove</button>
</div>
<div class="input string optional"><label for="virksomhed_pis" class="string optional">Pis</label><input type="text" size="50" name="virksomhed[v]" maxlength="255" id="virksomhed_pis" class="string optional"></div>
<div class="button-row" style="font-size: 11px; width: 110px; float: right; margin-top: -10px; margin-right: 16px;">
<button class="add" style="font-size: 11px;">Add info</button>
<button class="remove" style="font-size: 11px;">Remove</button>
</div>
How can I select the inputs fields in the new HTML and create the same functionality ?
There are two places you need to change.
The buttons that the handlers hook on to.
The way you get the last input field.
And there are some minor enhancements you can do:
Since the buttons are static, you can use click() to add event handler instead of live()
At three place you need to find the last input field relative to current button; making it a function would make it easier to understand and modify.
most jQuery set functions, including prop(), can take an object to set multiple values. This is usually better then calling the same function many times.
So, the final result:
function findLastInput ( element ) {
return $( element ).parent().prev().find('input').last();
}
$('button.add').click ( function(e) {
$(this).parent().find('button.remove').show();
$(this).hide();
var element = findLastInput(this).clone();
var name = element.prop('name');
var pattern = new RegExp(/\[(.*?)\]/);
var info = name.match(pattern)[1];
element.prop({
'value': '',
'name' : name.replace(pattern, '[' + info + 'info' + ']'),
'id' : element.prop('id') + 'info'
});
element.insertAfter(findLastInput(this));
})
$('button.remove').click ( function(e) {
$(this).parent().find('button.add').show();
$(this).hide();
findLastInput(this).remove('input');
});

Categories

Resources