I want to add a element with prepend jQuery - javascript

I want to add a new a element when I click the button but it doesnt work
<div id="add-container">
<input type="text"> <button>add</button>
<div id="megobrebi">
<a>Levani</a>
<a>Markozi</a>
<a>Zuka</a>
<a>Sandro</a>
</div>
</div>
$(document).ready(function() {
$('#add-container').on('click', 'button', function(){
var value = $('#add-container input').val;
var html = '<a>' + value + '</a>'
$('$megobrebi').prepend(html);
})
})

You have two errors in the handler for the click event on the button.
First, you need to call the jQuery val method in order to get the value of the input.
Second, the selector for the DOM element where you want to prepend is not right.
Therefore, the code should be:
$('#add-container').on('click', 'button', function(){
var value = $('#add-container input').val();
var html = '<a>' + value + '</a>'
$('#megobrebi').prepend(html);
})

The last line should be
$('#megobrebi').prepend(html);

Change your script code to
$(document).ready(function() {
$('#add-container button').on('click', function(e){
e.preventDefault(); // You may use this line if you wish to disable the default functionality button.
var value = $('#add-container input').val();
var html = '<a>' + value + '</a>';
$('#megobrebi').prepend(html);
});
});

Related

How can I remove the individual input box through the jquery remove function?

Here is my code. In that code the remove function works on only one input box, however I want that, it work on every input box which created through the append function.
<script>
$(document).ready(function(){
var one=1;
$("#add").click(function(){
one++;
$("#form_value").append("<div id=\"man"+one+"\"><br><input type=\"text\" placeholder=\"Product\"name=\"product["+one+"]\"><div class=\"w3-col l4\"> <input type=\"text\" placeholder=\"Product description\"></div><button type=\"button\" id=\"rem"+one+"\">Remove</button></div>");
$("#rem"+one+"").click(function(){
$("#man"+one+"").remove();
});
});
});
</script>
This happens because the value of one will increase each time you click on the add button, and this is the value that is used within the remove event.
If you add console.log(one) within the remove event you will see that one is always the last number.
A better way to do this would be to assign the div/remove elements to jquery objects and remove that instead.
e.g.
var one = 1;
$("#add").click(function() {
one++;
var $div = $("<div id='man" + one + "'></div>");
$div.append("<br><input type=\"text\" placeholder=\"Product\"name=\"product[" + one + "]\"><div class=\"w3-col l4\"> <input type=\"text\" placeholder=\"Product description\"></div>");
var $remove =
$("<button type='button' id='rem" + one + "'>Remove</button>")
.click(function() {
$div.remove();
});
$("#form_value").append($div.append($remove));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form_value"></div>
<button id="add">Add</button>

JQuery change id attribute of elements

I have a drag and drop thing which uses clone. I am having a problem with the date clone though because of datepicker. Therefore, I need to make sure each cloned datepicker has a unique id. A cloned element looks like the following
<div data-type="date" class="form-group">
<label class="control-label col-sm-5" for="dateInput">Date Input:</label>
<div class="col-sm-3">
<input type="text" name="dateInput[]" class="form-control date_picker" id="dateInput">
</div>
</div>
So if I clone two date inputs, I will have two of the above. Now on submit, I clean all of the cloned html, doing things like removing the data-type. At this stage, if there is a cloned date input, I need to give it a unique id. At the moment I am doing this
$("#content").find(".form-group").each(function() {
var html = $(this).attr('class', 'form-group')[0].outerHTML.replace(/ data-(.+)="(.+)"/g, "");
var input = $(this).find('input');
var i = 0;
if(input.attr('id') == 'dateInput') {
alert("TEST");
input.attr("id",'dateInput' + i).datepicker();
i++;
}
console.log(html);
dataArray.push(html);
});
The TEST alert fires twice as it should do if I clone 2 date inputs. However, the id attributes do not seem to change when I output the html to the console. I have set up the following Fiddle to demonstrate that the id of the element is not changing.
Any advice on getting this to change appreciated.
Thanks
Try defining dataArray, i outside out submit event, .each() , using .map() , .get() , .attr(function() {index, attr}) , .outerHTML
$(function() {
// define `i` , `dataArray`
var i = 0, dataArray = [];
$('#content').submit(function(event) {
event.preventDefault();
$("#content").find(".form-group").each(function() {
var html = $(this).attr('class', '.form-group')[0]
.outerHTML.replace(/ data-(.+)="(.+)"/g, "");
dataArray.push($(html).map(function(_, el) {
// adjust `input` `id` here , return `input` as string
return $(el).find("input").attr("id", function(_, id) {
return id + (++i)
})[0].outerHTML
}).get()[0])
});
$("#output")[0].textContent = dataArray.join(" ");
console.log(dataArray)
});
});
jsfiddle https://jsfiddle.net/mLgrfzaL/2/

Change attributes dynamically using jquery

I am running a loop which is appending input fields. Now, as I am using a loop, all the attributes are similars. So, when I need to grab any one of the then I am grabbing more than one field.
How do I dynamically change the attributes according to the index, so that I can grab the correct input field ?
ebs_no = data.number_ebs;
for(i=0;i<ebs_no;i++){
$('form.ebs').append("<br>EBS"+(i+1)+"</br>");
$('form.ebs').append('<br> SNAPSHOTNO <input type="text" name="'+i+'"></br>');
$('form.ebs').append('<input type="submit" name="submit">');
$('[name='+i+']').on('submit',function(){
alert($('[name='+i+']').val());
});
}
Replace this:
alert($('[name='+i+']').val());
by this:
alert($(this).val());
The code $(this) refers to the element being treated
Your are looking for event delegation.It is used for created Dynamically DOM elements and use class instead of iterare i in the loop
ebs_no = data.number_ebs;
for (i = 0; i < ebs_no; i++) {
$('form.ebs').append("<br>EBS" + (i + 1) + "</br>");
$('form.ebs').append('<br> SNAPSHOTNO <input type="text" class="someClass" name="' + i + '"></br>');
$('form.ebs').append('<input type="submit" name="submit">');
$('[name=' + i + ']').on('submit', function () {
alert($('[name=' + i + ']').val());
});
}
$(document).on('submit', '.someClass', function () {
alert($(this).val());
});

jQuery onclick add textbox value to div using the ID's

I am trying to add some textbox value to some other divs.
What I'd like to obtain is somthing like this:
textbox id = "text-box-name-1" ----> div id = "div-name-1"
textbox id = "text-box-name-2" ----> div id = "div-name-2"
textbox id = "text-box-name-3" ----> div id = "div-name-3"
and so on....
How can i do this? mind that the number of divs and textboxes are dynamically generated.!
Any suggestion will be really appreciated.
Thanks
EDIT
function test() {
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
for (var i = 0; i < rooms; i++) {
$("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
};
if ($('.housecontainer').find('.appendeddiv').length) {
$("#buttonaddrooms").hide();
}
};
i have already this code that allows me to create as many divs and textboxes as i type inside the textbox as value.
Now, i want be able to set, for example as div title, what the user type inside the textbox, and the only way that i've thought till now is using the id that are dynamically generated by the code that i already have.
Thanks for editing the post...
I would suggest first to add one class as an identifier to the Textbox and Div so we can attach event with the help of jQuery
$("<div class='appendeddiv targetDiv_"+ roomcounter +"'>Room-" + roomcounter + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' lang='textInput' class='targetText_"+ roomcounter +"'></div></br>").appendTo(".infoncontainer");
After that following script will do the trick :)
<script type='text/javascript>
$(function(){
$("input.textInput").on("keyup",function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
});
</script>
As per your fiddle If you want to update value mannualy onclick of any button then write this method.
<script type='text/javascript'>
function update(){
$("input.textInput").each(function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
}
</script>

onclick checkbox append checkbox value to URL

I wanna implement this using jquery instead of inline but Its not working, inline works fine. The other reason I wanna use jquery is if user selects more than one checkbox, the url should be appended with whatever is already there + OR '2nd CheckBox Value' like this:
"http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office OR Hospital"
The space infront and following OR is fine..
How can I achieve this? Can someone help me out?
Offices<input name="LocType" type="checkbox"
value="Office" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office'; return true;">  
Hospitals<input name="LocType" type="checkbox"
value="Hospital" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Hospital'; return true;">  
Facilities<input name="LocType" type="checkbox"
value="Facility" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Facility'; return true;">
Bind to the change event on the checkboxes. When clicked read the current checkbox value and then all other relative checkboxes. Append your base url with your custom query string and go crazy. :)
This isn't tested but hopefully it's a good starting point.
var baseUrl = 'http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ' OR ' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
You can try this.
HTML
<input name="LocType" type="checkbox" value="Office" />
<input name="LocType" type="checkbox" value="Hospital" />
<input name="LocType" type="checkbox" value="Facility" />
JS
Assuming you have a button or something on click of which you want to create a url with all the checked LocType checkbox values appended to the url seperated by OR
var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('button').click(function(){
//This will get the array containing values of checked LocType checkboxes
var checkedLocTypeValues = $('input[name=LocType]:checked').map(function(){
return this.value;
});
//Use Array.join() method to join the array elements by " OR "
url = url + "&k=" + checkedLocTypeValues.join(" OR ");
//Now you can use url variable which has all the checked LocType checkboxes value
}
jQuery map() reference - http://api.jquery.com/jQuery.map/

Categories