Trying to appending list items to dynamic id's - javascript

Hi I'm trying to add "children" list items to "family" lists. I have a first form to create the families and a second form which is a select box to create the children and add them to a selected family from the select box. The Ol's ids are dynamically created and the drop down's options dynamically created.
When an option is created, the values are incremented every time a family and option is made.
My plan is to reference the OL families by using the options, basically corresponding to the family by the time it is created.
For example when I make a family1, there will be an option created with that family1 with a value 1, and when family2 is created, an option 2 is created with a value of 2.
I'm trying to append children to the family but I have no idea how to reference the OL's ids
this is what I have so far
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
var i = 1;
$(document).on('click', "#submit", function () {
var str = ' '
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each(function () {
str = str + $(this).val() + ' ';
$(this).val('');
});
$("<ol>", {
text: str,
id: "family+" + i
}).appendTo("#container").append($('<button />', {
'class': 'btn2',
text: 'Remove'
}));
$('#select').append($('<option />', {
text: family,
value: i
}));
i++;
});
// Append items functions
$(document).on('click', "#submit2", function () {
var child = prompt("Please enter the child you want to add");
var e = document.getElementById("select");
var str = e.options[e.selectedIndex].value;
$('<li>', {
text: child
}).appendTo( ? ? ? ).append($('<button />', {
'class': 'btn',
text: 'Remove'
}))
});
//delete items functions
$(document).on('click', '.btn', function () {
$(this).closest('li').remove();
});
// delete the list
$(document).on('click', '.btn2', function () {
$(this).parent().next().remove();
$(this).closest('ol').remove();
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id = "child">
<select id ="select">
</select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id = "container">
</div>
</body>
</html>
Tip and help are appreciated
http://jsfiddle.net/Jnewguy/4LVTz/

Try
$(document).ready(function () {
var i = 1;
var $famname = $('#famname');
var $finputs = $('#family input[type = text]').not('#famname');
$(document).on('click', "#submit", function () {
var family = $famname.val();
var $ol = $("<ol>", {
id: "family-" + i
}).appendTo("#container");
$('<li />', {
text: family
}).append($('<button />', {
'class': 'btn2',
text: 'Remove'
})).appendTo($ol);
$finputs.each(function () {
$('<li />', {
text: this.value
}).appendTo($ol);
$(this).val('');
});
$('#select').append($('<option />', {
text: family,
value: i
}));
i++;
});
// Append items functions
var $select = $('#select')
$(document).on('click', "#submit2", function () {
var child = prompt("Please enter the child you want to add");
$('<li>', {
text: child
}).appendTo('#family-' + $select.val()).append($('<button />', {
'class': 'btn',
text: 'Remove'
}))
});
//delete items functions
$(document).on('click', '.btn', function () {
$(this).closest('li').remove();
});
// delete the list
$(document).on('click', '.btn2', function () {
$(this).parent().next().remove();
$(this).closest('ol').remove();
});
});
Demo: Fiddle

Related

Dropdown list in Jquery onClick

This code is for onclick to get dropdown and changes the text .
Everytime on change I want to post the value into database.
index.html
<div id='fullname'></div>
script.js
$('#fullname').click(function(){
var name = $(this).text();
$(this).html('');
$('<select>', { 'name': 'fname', 'id': 'txt_fullname'
})
.append($('<option>',
{'value':'Hardware_Problem','text':'Hardware_Problem'},'</option>'))
.append($('<option>', { 'value':'Software_Problem','text':'Software_Problem'},'</option>'))
.appendTo('#fullname');
$('#txt_fullname').focus();
});
$(document).on('blur','#txt_fullname', function(){
var name = $(this).val();
$('#fullname').text(name);
});

pass text to database using jquery

I'm display a text on screen and when I click it,I can edit the text using jquery. But I dunno how to reset the text that I edited to default and submit the text to database. If anyone know it please help me,thank in advance.
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
$(document).on('click', '.cmtedit', function (e) {
console.log(this);
TBox(this);
});
$("input").live('blur', function (e) {
RBox(this);
});
function TBox(obj) {
var id = $(obj).attr("id");
var tid = id.replace("cmt_edit_", "cmt_tedit_");
var input = $('<input />', { 'type': 'text', 'name': 'n' + tid, 'id': tid, 'class': 'text_box', 'value': $(obj).html() });
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var tid = id.replace("cmt_tedit_", "cmt_edit_");
var input = $('<p />', { 'id': tid, 'class': 'cmtedit', 'html': $(obj).val() });
$(obj).parent().append(input);
$(obj).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="sample">
<p id="cmt_edit_323" class="cmtedit">Sample Text</p>
</div>
<div>
<button type="reset" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-success" name="subtn">Submit</button>
</div>
</form>
Try this store the previous value with some variable .Then reset click add that previous value to function
var before;
jQuery.fn.extend({
live: function(event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
$(document).on('click', '.cmtedit', function(e) {
TBox(this);
});
$("input").live('blur', function(e) {
RBox(this);
});
$('.btn-primary').click(function() {
$("input").trigger('blur')
console.log(before)
$('.cmtedit').text(before)
})
function TBox(obj) {
before = $(obj).text()
console.log(before)
var id = $(obj).attr("id");
var tid = id.replace("cmt_edit_", "cmt_tedit_");
var input = $('<input />', {
'type': 'text',
'name': 'n' + tid,
'id': tid,
'class': 'text_box',
'value': $(obj).html()
});
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var tid = id.replace("cmt_tedit_", "cmt_edit_");
var input = $('<p />', {
'id': tid,
'class': 'cmtedit',
'html': $(obj).val()
});
$(obj).parent().append(input);
$(obj).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="sample">
<p id="cmt_edit_323" class="cmtedit">Sample Text</p>
</div>
<div>
<button type="reset" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-success" name="subtn">Submit</button>
</div>
</form>

Set different Attributes for Dynamic elements

How can I set Attributes to dynamically added buttons? I've tried but if I change attr all button types also bind together. I want to set {type:Submit} to first added button, {type:Reset} to second button, and {type:Cancel} to third button. How can I set different attr values to 3 different buttons?
Working DEMO
var app = angular.module('myapp', ['ngSanitize']);
app.controller('AddCtrl', function($scope, $compile) {
$scope.add_Button = function(index) {
var buttonhtml = '<div ng-click="selectButton()"><button id="button_Type">Button</button>//click//</div>';
var button = $compile(buttonhtml)($scope);
angular.element(document.getElementById('add')).append(button);
$scope.changeTosubmit = function () {
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "submit");
compile(el);
}
};
$scope.changeToreset = function () {
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "reset");
compile(el);
}
};
$scope.changeTocancel = function () {
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "cancel");
compile(el);
}
};
};
$scope.selectButton = function () {
$scope.showButton_Types = true;
};
});
function compile(element) {
var el = angular.element(element);
$scope = el.scope();
$injector = el.injector();
$injector.invoke(function ($compile) {
$compile(el)($scope);
});
};
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="AddCtrl">
<button ng-click="add_Button($index)">Add Buttons</button>
<hr>
<div id="add"></div>
<form ng-show="showButton_Types">
<div>
<label>change button types(?)</label><br/>
<input ng-click="changeTosubmit()" name="submit" type="radio"> Submit
<input ng-click="changeToreset()" name="submit" type="radio"> Reset
<input ng-click="changeTocancel()" name="submit" type="radio"> Cancel
</div>
</form>
</body>
</html>
I did quite research on this and here is the solution I came up with. I think this would be useful and perfectly match into your case. Instead if else you should have try AngularJs directives as below. For references visit
https://github.com/yearofmoo/angular-forms-refactor
and to understand how directive and its scope works here is perfect explanation with example visit
https://docs.angularjs.org/guide/compiler
angular.module('FieldEditor', [])
.controller("FieldEditorPageController",
function() {
var self = this;
this.fields = [{
type: 'submit'
}];
this.inputTypes = [{
value: "reset",
title: "button[reset]"
}, {
value: "cancel",
title: "button[cancel]"
}, {
value: "submit",
title: "button[submit]"
}];
this.newField = function() {
self.fields.push({
type: 'submit'
});
};
this.removeField = function(field) {
var index = self.fields.indexOf(field);
if (index >= 0) {
self.fields.splice(index, 1);
}
};
})
.controller("appButtonController", ['$scope', '$attrs',
function($scope, $attrs) {
var self = this;
var directiveScope = $scope.$parent;
this.options = directiveScope.$eval($attrs.model);
this.onOk = function() {
alert(self.options.type + ' button clicked');
}
}
])
.directive('appButton', function($compile) {
return {
transclude: true,
template: '<button ng-click="buttonCtrl.onOk()" type="">{{type|uppercase}}</button>',
scope: {
title: '#',
type: '#'
},
restrict: 'E',
replace: true,
controller: 'appButtonController',
controllerAs: 'buttonCtrl',
}
})
angular.module("MyApp", ['FieldEditor']);
<!doctype html>
<html>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="js/controller.js"></script>
<head>
<meta charset="utf-8" />
<title>
Dynamic Fields and Directive Binding
</title>
</head>
<body>
<div ng-app="MyApp">
<h1>Dynamic Fields and Directive Binding</h1>
<div ng-controller="FieldEditorPageController as pageCtrl">
<div>
<div ng-repeat="field in pageCtrl.fields track by $index">
<div>
<div>
{{ $index + 1 }}.
</div>
<div>
<div>
<label>Button Type:</label>
<select ng-model="field.type" ng-options="entry.value as entry.title for entry in pageCtrl.inputTypes" name="field_type" required>
</select>
<app-button type="{{field.type}}" text="button" model="field">
</app-button>
</div>
<div>
Remove
</div>
</div>
</div>
</div>
<div>
<span>
<a href="" ng-click="pageCtrl.newField()">
Add Button
</a>
</span>
</div>
</div>
</div>
</div>
</body>
</html>
Part of your problem is that you are creating elements that all have the same id.
From MDN:
The Element.id property represents the element's identifier, reflecting the id global attribute.
It must be unique in a document, and is often used to retrieve the element using getElementById. Other common usages of id include using the element's ID as a selector when styling the document with CSS.
-- Mozilla Developer Network -- Web API -- Element.id
So in your code create html with unique id attributes.
var buttonId = 0;
function buttonhtml() {
buttonId++;
return '<div ng-click="selectButton(' +buttonId+ ')">' +
'<button id="button-' +buttonId+ '">' +
'Button #' +buttonId+
'</button></div>';
};
var button = $compile(buttonhtml())($scope);
By doing this you will be creating conformant HTML and you will be able to change specific button attributes using getElementById.

get child id from parent javascript onclick

I have the script bellow and i want to get the id of the child removed
<div class="right respleft">
<div class="section-title" id="divin">Ajout d'un champ</div>
<form class="tiny_form" id="form-step2">
<input type="text" id="fiel" placeholder="Nom du champ" /><br/>
<select class="form-control" id="champs">
</select>
<i class="fa fa-plus"></i><br/>
<div id="extender"></div>
</form>
</div>
<div class="sep seppage"></div>
<div class="clear"></div>
<div id="bottom-submit" class="inner clear">
<input type="submit" class="page-next center btn btn-lg btn-default" value="Créer" />
</div>
{% endblock %}
{% block javascripts %}
<script>
//add input
$('a#add_btn').click(function () {
var x = document.getElementById("fiel");
var selected= x.value;
var c = document.getElementById("champs");
// var option = document.createElement("option");
var strUser = document.getElementById("champs").value;
var valChamps=document.getElementById("fiel").value;
$('<p><input type="text" class="highlight_orange" name="items[]" id="' + strUser+ '" value="' + valChamps+ '" />' +
'<a class="delete" href="#step2" id="' + strUser + '"><i class="fa fa-trash-o"></i></a></p>').fadeIn("slow").appendTo('#extender');
c.remove(c.selectedIndex);
i++;
return false;
});
//fadeout selected item and remove
$("#form-step2").on('click', '.delete', function () {
var item = $(this).closest('input');
var id = item.attr('id');
$(this).parent().fadeOut(300, function () {
$(this).empty();
return false;
});
});
function addList(){
var select = document.getElementById("champs");
for(var i = 100; i > 0; --i) {
var option = document.createElement('option');
option.text = 'champ libre '+i;
option.value =i;
select.add(option, 0);
}
}
addList();
</script>
my problems is how to get the id of the removed input text after clicking on remove button.
this is picture of the output
output
Thanks for your helps
You can use siblings method to get the id of input element
//fadeout selected item and remove
$("#form-step2").on('click', '.dynamic-link', function () {
var myId = $(this).siblings('input[type=text]').attr('id');
alert(myId)
$(this).parent().fadeOut(300, function () {
$(this).empty();
return false;
});
});
You can use getAttribute() function:
// your stuff
var myId = c.getAttribute("id");
c.remove(c.selectedIndex);
// more stuff
EDIT
Maybe you need it here:
//fadeout selected item and remove
$("#form-step2").on('click', '.delete', function () {
$(this).parent().fadeOut(300, function () {
var myId = $(this).attr('id');
$(this).empty();
return false;
});
});
Be more specific please
EDIT2
That's the solution:
//fadeout selected item and remove
$("#form-step2").on('click', '.delete', function () {
$(this).parent().fadeOut(300, function () {
var myId = $(this).find('input[type=text]').attr('id');
$(this).empty();
return false;
});
});
See it working: http://jsfiddle.net/vWPJf/57/

Multiple select in jQuery

I'm trying to write a jQuery code that works in this way:
When the page is loaded, it is presents only one field.
Selecting an option from that field, a new field is opened and the option have to be all the option of the first , except the option selected. And so on, also for the other created.
The jsfiddle is shown here
var globalObj = {};
var selectedObj = {};
var unselectedObj = {};
var currentSelection = "";
function deleteByVal(obj,val) {
for (var key in obj) {
if (obj[key] == val) delete obj[key];
}
}
$(document).ready(function () {
$(document).on('click', 'target', function(){
var curSelected = $(this).find(":selected").text();
});
$("#select1").one('click',function(){
$(this).children().each(function () {
globalObj[this.value] = this.innerHTML;
});
unselectedObj = globalObj;
});
$(document).on('change', '.prova > .target', function () {
$('div').removeClass('prova');
var $mySelect = $('<select>', {
class: 'target'
});
var selectedValue = $(this).find(":selected").text();
var found = 0;
$.each(selectedObj, function (val, text) {
if (val === selectedValue) {
found++;
}
});
if (found===0) {
selectedObj[this.value] = selectedValue;
deleteByVal(unselectedObj,selectedValue);
}
console.log(selectedValue);
console.log(selectedObj);
console.log(unselectedObj);
var obj = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML!=selectedValue) {
//code
obj[this.value] = this.innerHTML;
}
});
console.log("Questo rappresenta obj:");
console.log(obj);
console.log("stampa obj conclusa");
$( "select" ).not(this).each(function( index ) {
var temp = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
$this = $(this);
console.log("stampa temp");
console.log(temp);
console.log("fine stampa temp");
});
$.each(unselectedObj, function (val, text) {
$mySelect.append($('<option />', {
value: val,
text: text
}));
});
var $input = $('<input>', {
type: 'number',
style: 'width: 35px',
min: '1',
max: '99',
value: '1'
});
var $button = $('<button>', {
type: 'button',
class: 'remove_item',
text: 'delete'
});
$(this).parent().after($('<br>', {
class: 'acapo'
}), $('<div>', {
class: 'prova'
}).append($mySelect, $input, $button));
$(this).unbind('change');
$(this).unbind('click');
$(this).on('click', function(){
currentSelection = $(this).find(":selected").text();
});
$(this).on('change',function(){
console.log("nuovo bind");
var selectedValue = $(this).find(":selected").text();
if (currentSelection !== selectedValue) {
console.log(currentSelection + " to "+ selectedValue);
$( "select" ).not(this).each(function( index ) {
$(this).append($('<option />', {
value: currentSelection,
text: currentSelection
}));
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
});
}
});
});
});
The code has some problems and I was thinking to use an existing plugin instead of that code. Is there anyone that knows a plug-in which makes that work?
Here's an option using javascript templating. I'm declaring my available options at the top in an array, thus separating my data model from the UI. I'm using the handlebars library to then compile a template and append it into the DOM. Fiddle: http://jsfiddle.net/LNP8d/1/
HTML/Handlebars
<script id="select-template" type="text/x-handlebars-template">
<div>
<select class="target" id ="select-{{id}}">
<option value="">Select an option…</option>
{{#each options}}
{{#unless selected}}
<option data-option-key="{{#key}}" value="{{value}}">{{label}}</option>
{{/unless}}
{{/each}}
</select>
<input type="number" style="width: 35px" min="1" max="99" value="1">
</div>
</script>
<div id="container">
</div>
Javascript
//Declare the available options
var options = {
option1: {
value: 1,
label: "Option 1"
},
option2: {
value: 2,
label: "Option 2"
},
option3: {
value: 3,
label: "Option 3"
},
option4: {
value: 4,
label: "Option 4"
},
}
source = $("#select-template").html(),
template = Handlebars.compile(source),
onScreen = 0;
//Adds another select menu
var showSelect = function(){
onScreen++;
$("#container").append(template({id:onScreen, options:options}))
};
//Listens to change events
$("body").on("change", ".target", function(){
options[$(this).find(":selected").data("option-key")].selected = true;
showSelect();
});
//Initialises the UI
showSelect();
Please note: this is not a complete example. If you decide to use this method, you'll need to add some checks for what happens when the options run out and if someone changes an option. I hope it's successful in showing you an alternative a potentially more flexible method though.
I think you are looking for something like this:
http://codeassembly.com/Simple-chained-combobox-plugin-for-jQuery/

Categories

Resources