i want to add element to div in angularjs. so write this code but not work correctly. thanks for your help :)
function TestController($scope) {
$scope.addElement = function(){
var myElements = angular.element(document.querySelector('#form'));
console.log(myElements);
if(myElements.length == 0)
alert("Not Find");
else
myElements.prepend( myElements[0].children[1]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="TestController" id="form">
<input type="button" ng-click="addElement()" value="add"></input>
<div id="div">
<input type="text" name="name">
</div>
</div>
Here is what I have tried.
$scope.addElement = function(){
var myElements = angular.element(document.querySelector('#form'));
console.log(myElements)
console.log(myElements[0].children[1])
if(myElements.length == 0)
alert("Not Find");
else{
html = angular.element(myElements[0].children[1]).clone();
myElements.append( html);
}
You should use angular clone method.
EDIT.
Here it the Plunker
If I understood your question correctly, you want to append an input element to div on each ng-click?
You just need to target the div with jquery and append the element with it.
See example: http://jsbin.com/seyawemijo/edit?html,js,output
Often than not when you want to modify the DOM directly, there is a way to do it without.
"Thinking in Angular way"
function TestController($scope) {
$scope.textArr = [];
var count = 1;
$scope.addElement = function() {
var ele = {
model: 'hello ' + count++
}
$scope.textArr.push(ele);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="TestController" id="form">
<input type="button" ng-click="addElement()" value="add" />
<div ng-repeat="text in textArr">
<input type="text" ng-model="text.model">
</div>
<div>{{textArr}}</div>
</div>
Try this one
myElements.prepend(myElements[0].children[1].value);
I have altered the above solution to add other attributes(including id) to the input text element
var globalCntr = 0;
function TestController($scope) {
$scope.addElement = function() {
globalCntr ++;
$('<input>',{
type:'text',
id:('inputText'+globalCntr)
}).appendTo($('#target'));
};
}
Related
HTML:
<div class="col answer">
some text
</div>
js:
$(".answer").text("Here we change the text" );
$(".answer").click(function(E) {
console.log(E).html();
});
console output : undefined
You need to use $(this).html() not (E).html(). Your code should look like this:
console.log($(this).html());
Demonstration:
$(".answer").text("Here we change the text");
$(".answer").click(function() {
console.log($(this).html());
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="col answer">
some text
</div>
Since this was also posted in Javascript here's a vanilla option to do the same:
<div class="col answer">
some text
</div>
<script>
var x = document.getElementsByClassName("answer");
var y;
for (y = 0; y < x.length; y++) {
x[y].innerHTML = "Here we change the text";
}
window.onload = function() {
document.addEventListener('click', function (event) {
var target = event.target;
if(target.matches('.answer')){
console.log(target.innerHTML);
}
}, false);
}
</script>
Do you need innerHTML or text?? If you need text use .text() method.
$(".answer").text("Here we change the text" );
$(".answer").off().on('click',function() {
console.log($(this).html());
});
I have a simple search box. When the input box is not empty a delete button shows up to remove the text inside the box. After that the button should disappear again until i type something in the box again.
When i manually remove the text the delete box is disappearing, but when i press the delete button its not working. Do i have to use .length? I was using .value before like that: if ($(".form-control").value == '' || $(".form-control").value == $(".form-control").defaultValue) {
Thanks in advance.
a = $scope
a.change = function () {
a.limit = 6;
var x = a.search;
if (x.length == '') {
$(".form-inline").removeClass("isset");
} else {
$(".form-inline").addClass("isset");
}
};
a.clearSearch = function () {
a.search = "";
a.limit = 6;
};
html part:
<input type="search" ng-change="change()" ng-model="search" class="form-control" placeholder="Labor durchsuchen...">
<div class="icon-close" ng-click="clearSearch()"></div>
You can use ng-class for that what you are doing with JQuery:-
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.formData = {};
$scope.change = function () {
//do anything here
};
$scope.clearSearch = function () {
$scope.formData.search = "";
};
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="search" ng-class="(formData.search != undefined && formData.search)?'isset':''" ng-change="change()" ng-model="formData.search" class="form-control" placeholder="Labor durchsuchen...">
<div class="icon-close" ng-click="clearSearch()"></div>
</div>
You should be able to drop the jQuery code and just use
<div class="icon-close" ng-click="clearSearch()" ng-show="search.length===0"></div>
I think you need to trigger your a.change function inside a.cleanSearch to check again if something is typed or not.
a.clearSearch = function () {
a.search = "";
a.limit = 6;
a.change()
};
I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
}
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/
im very new at javascipt (im php developer) so im really confused trying to get this working.
In my web form i have 3 textfields (name, description and year) that i need to let the user add as many he needs, clicking on a web link, also, any new group of text fields need to have a new link on the side for removing it (remove me).
I tried some tutorial and some similar questions on stackoverflow but i dont get it well. If you can show me a code example just with this function i may understand the principle. Thanks for any help!
this is the simplest thing that has come to my mind, you can use it as a starting point:
HTML
<div class='container'>
Name<input type='text' name='name[]'>
Year<input type='text' name='year[]'>
Description<input type='text' name='description[]'>
</div>
<button id='add'>Add</button>
<button id='remove'>Remove</button>
jQuery
function checkRemove() {
if ($('div.container').length == 1) {
$('#remove').hide();
} else {
$('#remove').show();
}
};
$(document).ready(function() {
checkRemove()
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
checkRemove();
});
$('#remove').click(function() {
$('div.container:last').remove();
checkRemove();
});
});
fiddle here: http://jsfiddle.net/Fc3ET/
In this way you take advantage of the fact that in PHP you can post arrays: server side you just have to iterate on $_POST['name'] to access the various submissions
EDIT - the following code is a different twist: you have a remove button for each group:
$(document).ready(function() {
var removeButton = "<button id='remove'>Remove</button>";
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
$('div.container:last').append(removeButton);
});
$('#remove').live('click', function() {
$(this).closest('div.container').remove();
});
});
Fiddle http://jsfiddle.net/Fc3ET/2/
jsFidde using append and live
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var html = "<div>" + '<input name="name{0}" type="text" />' + '<input name="description{1}" type="text" />' + '<input name="year{2}" type="text" />' + '<input type="button" value="remove" class="remove" />' + '</div>',
index = 0;
$(document).ready(function() {
$('.adder').click(function() {
addElements();
})
addElements();
$('.remove').live('click', function() {
$(this).parent().remove();
})
});
function addElements() {
$('#content').append(String.format(html, index, index, index));
index = index + 1;
}
Look at this: http://jsfiddle.net/MkCtV/8/ (updated)
The only thing to remember, though, is that all your cloned form fields will have the same names. However, you can split those up and iterate through them server-side.
JavaScript:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#addnew").click(function(e) {
$("#firstrow").clone() // copy the #firstrow
.removeAttr("id") // remove the duplicate ID
.append('<a class="remover" href="#">Remove</a>') // add a "remove" link
.insertAfter("#firstrow"); // add to the form
e.preventDefault();
});
$(".remover").live("click",function(e) {
// .live() acts on .removers that aren't created yet
$(this).parent().remove(); // remove the parent div
e.preventDefault();
});
});
</script>
HTML:
Add New Row
<form id="myform">
<div id="firstrow">
Name: <input type="text" name="name[]" size="5">
Year: <input type="text" name="year[]" size="4">
Description: <input type="text" name="desc[]" size="6">
</div>
<div>
<input type="submit">
</div>
</form>
Try enclosing them in a div element and then you can just remove the entire div.
Try this
Markup
<div class="inputFields">
..All the input fields here
</div>
Add
<div class="additionalFields">
</div>
JS
$("#add").click(function(){
var $clone = $(".inputFields").clone(true);
$clone.append($("<span>Remove</span").click(functio(){
$(this).closest(".inputFields").remove();
}));
$(".additionalFields").append($clone);
});
There are 2 plugins you may consider:
jQuery Repeater
jquery.repeatable
This question has been posted almost 4 years ago. I just provide the info in case someone needs it.
I have a structure that looks like the one below, I'm trying to get the id foo. It is the only DIV with id if we bubble up from the onclick func(), which means that there wont be other DIVs that contain an id inside foo. However, there can be other tags inside foo that contain an id (such as bye, hello).
No frameworks are being used.
<div id="bar"></div>
<div id="foo">
<p><p>
<div class="bye">
<input id="bye" type="text" value="test" />
<input id="hello" type="text" value="test" />
<table>
<tr><td onclick="func(event)">1</td></tr>
<tr><td onclick="func(event)">2</td></tr>
</table>
</div>
</div>
function findIdOfParent(obj) {
var o = obj;
while(!o.id) {
o = o.parentNode;
}
alert(o.id); // 'foo'
}
The function findIdOfParent takes a DOM node. You could call it with onclick="findIdOfParent(this);", but if you only want to pass event, as in your example, you'd have to extract the DOM node from event.target or whatever you're currently doing.
This should do it:
<div id="bar"></div>
<div id="foo">
<p><p>
<div class="bye">
<input id="bye" type="text" value="test" />
<input id="hello" type="text" value="test" />
<table>
<tr><td onclick="func(this)">1</td></tr>
<tr><td onclick="func(this)">2</td></tr>
</table>
</div>
</div>
<script type="text/javascript">
function func(elt) {
// Traverse up until root hit or DIV with ID found
while (elt && (elt.tagName != "DIV" || !elt.id))
elt = elt.parentNode;
if (elt) // Check we found a DIV with an ID
alert(elt.id);
}
</script>
You could use the parentNode property of the clicked element to iterate up through the DOM tree.
ie:
<td onclick="func(this)">
function func(item)
{
var parent = item.parentNode;
// and so on, or something similar
var divId = div.id;
}
elem is the element that call the function on click
var found = false;
var myId = "";
while (elem &&!found) {
if (elem.id){
found = true;
myId = elem.id;
}
elem = elem.parentNode;
}
Can't you apply a simpler pattern? Instead of having onclick properties in your cells, attach a single click handler to your outermost div(s), then you just need to refer to this:
document.getElementById("foo").onclick = function(event) {
if(e.target.tagName.toLowerCase() == "td") {
alert(this.id);
}
};
http://jsfiddle.net/fRxYB/
Or am I completely missing the point?
To have a somewhat more generic version, I'd suggest this:
function func(event) {
var par = findTop(event.target);
console.log(par);
};
function findTop(node) {
while(node.parentNode && node.parentNode.nodeName !== 'BODY') {
node = node.parentNode;
}
return node;
}
example: http://www.jsfiddle.net/4yUqL/37/