I am trying to change just the label tag when I clone the div. The current piece of JS changes the product name within the drop down list.
var clone = $('#product-1').clone(false)[0].outerHTML.replace(/1/g, counter);
<div class="activeingredients">
<div class="products" id="product-1">
<label>Active Ingredient 1</label>
<ul>
<li style="display:inline-block">
<select name="productid">
<option>Product 1</option>
</select>
</li>
</ul>
</div>
</div>
http://jsfiddle.net/ehv1xmL6/
Thanks
There are several ways to do this, including just having a string without a number ready to replace the label text. However, following what you already have I made the following changes:
I first added a class to the label to make it easier to select. Your current code selects all numbers inside the div.
<label class="ingredientLabel">Active Ingredient 1</label>
Second, I cloned the div. Then selected the html inside of .ingredientLabel and changed the number using Regex. I changed the regex to find any number inside the string and not just '1' in case the number changes for some reason.
$(document).ready(function(){
var counter = 1;
$("#addproduct").click(function(){
counter+= 1;
var clone = $('#product-1').clone(false);
clone.find(".ingredientLabel").html(clone.find(".ingredientLabel").html().replace(/[0-9]+/g, counter));
$(clone).appendTo(".activeingredients")
});
});
Here is the working fiddle: JSFiddle
Related
Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";
Below is my html:
<div class="row">
<div class="col-lg-11">
<ul class="list-unstyled" id="slider">
</ul>
</div>
</div>
Below is my javascript:
var locationbegin="<div class='form-group'><label>Location</label><select
class='form-control' id='location'><option>test</option>";
$("#slider").append(locationbegin);
var locationoptions = "<option>tester</option>";
$("#slider").append(locationoptions);
var locationend="</select> </div>";
$("#slider").append(locationend);
Below is the output:
The problem is the tester comes out of the location dropdown. I'm not sure where i'm going wrong. You can also use http://rendera.herokuapp.com/ to render the code.
Edit: The reason the javascript is separated is because of some other javascript code in between in the code.
You are going wrong in not using proper HTML. You have to close the tags or the browser does this for you whenever it computes it should. append first turns your HTML into NodeList (which results in the select and div being closed) and afterwards i is appended to the slider. Now, if you append further options onto that HTML structure, you are ffectivly appending thos behind the closed div.
You should keep a reference to the select to be able to add more optinos whenever you like:
a) create the surrounding markup:
var myFormField = $('<div class="form-group"><label>Location</label><select class="form-control" id="location"><option>test</option></select></div>')
b) find the select and store it to a variable:
var mySelect = myFormField.find('#location');
c) add as many options as you like
mySelect.append('<option>Value 2</option>');
mySelect.append('<option>Value 3</option>');
mySelect.append('<option>Value 4</option>');
Oh this is not how it works. .append will automatically add closing tags if your HTML strings doesnt have it.
So just after the first append call, your html will become:
<div class='form-group'>
<label>Location</label>
<select class='form-control' id='location'>
<option>test</option>
</select>
</div>
And further insertions will happen after this HTML.
So instead, do this:
var locationbegin="<div class='form-group'><label>Location</label><select
class='form-control' id='location'><option>test</option>";
var locationoptions = "<option>tester</option>";
var locationend="</select> </div>";
$("#slider").append(locationbegin + locationoptions + locationend);
I got the following HTML:
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:
var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);
It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.
If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.
Thank you.
EDIT:
There has been a similar thread before, here is a working solution:
https://jsfiddle.net/hallleron/wg1pbwbf/2/
Basically you loop through the siblings in the selection to get each value and then parse the array as string to display it in my result paragraph for better visuals.
ORIGINAL:
If you want a jQuery-free version, here is a fiddle: https://jsfiddle.net/hallleron/wg1pbwbf/
The whole Javascript Part is the following:
document.getElementById('editable_phrase').addEventListener("click", getDataId);
function getDataId(){
console.log(window.getSelection().anchorNode.parentElement.attributes[0].nodeValue);
}
So every time the event listener detects a click, it gets the selected text/span and extracts its data-id attribute from the object.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
<script>
$('#editable_phrase').on('click','span',function(){
var res = $(this).attr('data-id');
alert(res);
})
</script>
I am trying to use angularjs dynamic form elements but when I type something in inputs, there are appearing many special characters []"": and field, value .etc in textarea, I just want to see in textarea what I wrote in inputs ,
this is what I am working on it http://plnkr.co/edit/JbjqjAoQ3odBhXF1a13r?p=preview
sorry for my poor english,,,
What Chris Story says is correct. You are trying to model the text value of the <textarea> to an array of objects, inputs
If you are just trying to display the results like it seems, a <textarea> is not the way to go. You can display them in a simple list, like this:
<ul>
<li ng-repeat="input in inputs">{{input.field}} = {{input.value}}</li>
</ul>
EDIT
To display it in a <textarea>, you will need to store the list as string to use. This can be done by appending each item into a single string each time there is a change to an input value using ng-change.
Change the inputs to utilize the ng-change:
<div ng-repeat="input in inputs">
<input type="text" ng-model="input.field" ng-change="inputChanged()" />
<input type="text" ng-model="input.value" ng-change="inputChanged()" />
<button ng-click="removeInput($index); inputChanged()">Remove</button>
</div>
And create the function that is called to maintain the string:
$scope.inputChanged = function() {
$scope.listString = "";
for(var i = 0; i < $scope.inputs.length; i++) {
var field = $scope.inputs[i].field;
var value = $scope.inputs[i].value;
$scope.listString += field + " = " + value + "; ";
}
}
And finally, use this $scope.listString in the <textarea>:
<textarea rows="22" cols="55" ng-model="listString"></textarea>
I have forked your Plunkr here
The behavior does not make much sense from a UX perspective, but this seems to match your requirement. An option that might make sense is to add disabled="true" to the <textarea> so it can not be edited.
The issue is that you are rendering {{inputs}} and inputs is an Array.
My attempt to find the name of the div holding a select box, then put this div into a variable which is used elsewhere in my jQuery code, does not seem to be working. Another piece of code is appending extra divs to the page, these have select boxes of class .parent within them. However many extra divs I append, the code below always appends to the first div added, even though checking through a browser the div structure works as expected. I'm new to jQuery so don't know if I'm missing something obvious, but I'm pretty sure the variable div below should be redefined each time .parent element is changed as it is part of the variable's definition. When I've run an alert just to check the variable name it is always defined as sub_cat_1. This is correct for the first appended div class of show_sub_categories but thereafter it should be sub_cat_2, sub_cat_3 etc incrementing. As said the select boxes are definitely in the correct divs on the page, so I can only asssume I'm missing something simple with this bit of the code below. (basic html at bottom for reference)
$('.parent').livequery('change', function () {
var div = $(".parent").closest("div").attr("id");
$(this).nextAll('.parent').remove();
$(this).nextAll('input').remove();
alert(div);
$('#' + div).append('<img src="images/system/loader2323.gif" style="float:left" id="loader" alt="" />');
$.post("get_chid_categories.php", {
parent_id: $(this).val(),
}, function (response) {
setTimeout(function () {
finishAjax(div, response);
}, 400);
});
return false;
});
This is just to show you the basic structure of the divs being appended.
<p id="add_field"> … </p>
<div class="show_sub_categories">
<div id="sub_cat_1">
<select class="parent" name="search_category"> … </select>
<select class="parent" name="sub_category"> … </select>
</div>
</div>
<div class="show_sub_categories">
<div id="sub_cat_2">
<select class="parent" name="search_category"> … </select>
<select class="parent" name="sub_category"> … </select>
</div>
</div>
I've put a very simplified version of this at http://www.0urs.com/fiddle/experience1.php just to illustrate the physical location of the appended select boxes.