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

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>

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>

Javascript function for form created using Javascript

I have a script which adds a new form when a button is clicked to a HTML page with the code as following:
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("Max number of forms, " + counter );
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<form name='frmMain' action='prelucrare.php' method='POST'><div class='slot' id='dynamicInput' align='center'> Masina " + (counter +1 ) + "<table border='1'><tr><td align='right'><label for='marca'>Marca:</label></td><td colspan='2' align='left'>"
+ "<select id='marc' name='marc'><option selected value=''></option>"
+ "<tr><td align='right'><label for='motorizare1'> Motorizare:</label></td> <td><input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id=motor1 oninput='outputUpdate1(value)'></td><td><output for=motorizare1 id=moto1>2</output></td></tr>"
+ "</div></form>"
;
}
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
<input type="button" value="Adauga" onClick="addInput('dynamicInput');">
And I have the script bellow which changes the value from the slider.
<script>
function outputUpdate1(mot1) {
document.querySelector('#moto1').innerHTML = mot1;
}
</script>
My problem is that the JS code only changes the input for the first form, even if the slider is activated from another form. In short, the slider should return the value in the form from which it is activate; not only in the first form added.
Thank you!
Going along with my comment, the problem is stemming from the id value being the same across all of your output elements (moto1). You've actually got all the variables you need to make them unique since you're tracking a count of the number of forms on the page (your counter variable). You can use this in place of your current output HTML:
"<input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id='motor_" + counter + "' oninput='outputUpdate1(value)'/>"
"<output for=motorizare1 id='moto_" + counter + "'>"
You can update your function to parse out the correct index for the output you want to update since they should be in sync if you use the HTML above:
function outputUpdate1(mot) {
// Get the counter part of the range element's id
var index = mot.id.split('_')[1];
document.querySelector('#moto_' + index).innerHTML = mot;
}
You may need to make some tweaks to code you haven't provided in the question, but that's one way of making the id values unique and how to access them without knowing the exact id ahead of time.

How do i output link under each catergory with each drop down menu item

`
$(function(){
$('.addLink').click(function(e){
e.preventDefault();
var content = $('.categorySelect');
var url = $("#userInput").val();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
$(link).appendTo('.sports');
});
});
Choose Category:
<select class='categorySelect'>
<option value="Sports" id="a">Sports</option>
<option value="World" id="b">World</option>
<option value="Movies" id="c">Movies</option>
</select><br />
<input type='text' id='userInput' placeholder='Enter Link Here' />
<input type='button' value='Add' class='addLink'/>
<div class='sports'>
Sports:
</div>
<div class='world'><br />
World:
</div>
<div class='movies'><br />
Movies:
</div>
</div>
`heres what i have now. when the user chooses a catergory from the dropdown menu their typed in link will show under that caterory(div class). i cant seem to figure this out.
$('.addLink').click(function () {
var content = $('.categorySelect').val().toLowerCase();
var url = $("#userInput").val();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
$(link).appendTo('.'+content);
});
jsFiddle Demo
First, you don't need event.preventDefault() because the input field doesn't have a default action that needs to be suppressed (cf. the a tag, which does).
Next, you need to grab the value of the SELECT and convert to lowercase, since that is the case of the class.
To append to the correct class, you concat the . class indicator to the name of the class extracted from the SELECT option value.
If you wanted to make the action automatic upon selection of a category, then change this:
$('.addLink').click(function () {
to this:
$('.categorySelect').change(function () {
Revised jsFiddle
Note how we can use $(this) to refer to the control that triggered the event. By using $(this), we can chain jQuery methods, e.g.
var content = $(this).val();
If all we want is the value, we can use pure javascript as it is a bit faster:
var content = this.value;
Since .toLowerCase() is pure javascript, we can still go with this.value
var content = this.value.toLowerCase();
I have wrote some working code for you, with comments included on Fiddle:
$(function(){
$('.addLink').click(function(e){
e.preventDefault();
/*
Select the value of the dropdown (lowercase the values because your
HTML classes are written lowercase) and the values of your dropdown are not.
*/
var content = $('.categorySelect').val().toLowerCase();
var url = $("#userInput").val().toLowerCase();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
//Save check if the user has filled in a URL.
if(url !== '')
//append URL link to the selected value of the dropdown.
$(link).appendTo('.'+content);
});
});
http://jsfiddle.net/9fc8zb4b/

Radio Input gets unchecked after jQuery html operation

I'm getting an extremely weird error. My radio button gets unchecked after doing the following operations:
var $page = $('[data-shortcode-page="' + shortcode + '"]', $webrock).html();
//CHECKED
console.log($('[data-shortcode-page="' + shortcode + '"] :checked', $webrock).length)
$('.webrock-page-content', $addPage).replaceWith($page);
//UNCHECKED
console.log($('[data-shortcode-page="' + shortcode + '"] :checked', $webrock).length)
Does anyone know why this is happening? Here's a jsFiddle: http://jsfiddle.net/mVB2q/1/
Thank you very much!
You are cloning a radio group with the same name. You need to update the name of the cloned radio group. Here is a simple solution where I am hardcoding in "test1" for the new group name, but you may want to modify it to fit your needs:
var shortcode = 'object';
var $page = $('[data-shortcode-page="' + shortcode + '"]');
console.log($('[data-shortcode-page="' + shortcode + '"] :checked').length);
//after cloning the radio buttons, find radio buttons and update the name attribute.
$('.webrock-page-content').html($page.clone().find("input[type='radio']").attr("name", "test1").end().html());
console.log($('[data-shortcode-page="' + shortcode + '"] :checked').length);
Updated fiddle.

How can I make this feature faster in Javascript?

I have created a highlight feature that will highlight anything contained in a <p> red using a user specified keyword. When the submit button is clicked Javascript/jQuery pull the keyword from the input field and compare it to any lines that conain it and then highlight those lines red. It works great... but its slow. Is there another way to do this that is faster when working with over 1000 lines of <p>?
HTML
Keyword: <input type="text" id="highlight_box" class="text_box" value="--Text--" />
<input type="button" id="highlight" value="Highlight" />
<!--Print area for the Access log-->
<div id="access_content" class="tabbed-content">
<ul id="access-keywords-row" class="keywords-row">
<!--When a user submits a keyword it is placed as a tag here so it can be deleted later-->
</ul><br /><br />
<div id="access_log_print" class="print-area">
<p>Some Content</p>
<p>Some more content</p>
<!--Most of the time this could contain 1000's of lines-->
</div>
</div>
JavaScript
//add highlight and tag
$("#highlight").click(
function(){
var id = $("#highlight_box").val();
if(id == "--Text--" || id == ""){
alert("Please enter text before highlighting.");
}else{
$("#access-keywords-row").append("<li><img src=\"images/delete.png\" class=\"delete_filter\" value=\"" + id + "\" /> " + id + " </li>");
$("#access_log_print p:containsi(" + id + ")").css("color","red"); }
});
//remove highlight and tag
$(".keywords-row").on("click", ".delete_filter",
function() {
var val = $(this).val();
//remove element from HTML
$(this).parent().remove();
$("#access_log_print p:containsi(" + val + ")").css("color","black");
});
Adding color, red means adding the style attribute to each p, I think this can be improved adding a class:
p.highlight {
color:red;
}
And replacing
$("#access_log_print p:contains(" + id + ")").css("color","red");
by
$("#access_log_print p:contains(" + id + ")").addClass('highlight');
This probably speeds a little bit the process
I've written a small solution using jQuery's contains() method. Obviously you can throw in some string validation.
http://jsfiddle.net/W2CZB/
Try defining a css class, e.g.:
.red{background-color:#f00;}
and then instead of adding to each "style=background-color:#f00;" you will just .addClass("red");
just less code to put, but still jQuery will have to go thru all lines and if it is a lot then I guess it depends on your machine speed ;)
The following solution will probably increase performance at the cost of space. It works by building a word mapping of the lines and accessing directly to add or remove the highlight class. This solution also keeps a count of the number of times a filter hit that line so it stays highlighted until the last filter is removed. I have tested with a few lines, I am not sure how will it perform with 1000s. You tell us :)
$(function(){
buildIndex();
$("#highlight").click(
function(){
var id = $("#highlight_box").val();
if(id == "--Text--" || id == ""){
alert("Please enter text before highlighting.");
}else{
var filter = $("<li><img src=\"images/delete.png\" class=\"delete_filter\" value=\"" + id + "\" /> " + id + " </li>");
filter.click(function(){
$(this).remove();
removeHighlight(id)
});
$("#access-keywords-row").append(filter);
$.each(index[id], function(i,line){
if (line.highlightCount)
line.highlightCount++;
else {
line.addClass('highlight')
line.highlightCount=1;
}
});
}
});
function removeHighlight(id) {
$.each(index[id], function(i,line){
line.highlightCount--;
if (line.highlightCount<1)
line.removeClass('highlight')
});
};
});
var index={};
function buildIndex(){
$("#access_log_print p").each(function(i) {
var line = $(this)
var words = line.text().split(/\W+/);
$.each(words, function(i,word){
if (!index[word]) { index[word]=[]; }
index[word].push(line);
});
});
}

Categories