Insert one HTML element before another jQuery - javascript

I wonder how to insert an HTML element before another with jQuery.
It is also important to be able to get the content of the new element out of an input.
Something like that, but working :
var input = $("#theInput").val();
var content = document.createElement("p");
content.appendChild(document.createTextNode(input));
$("div").insertBefore(content);

Try this:
$("div").prepend(content);

See below example:
HTML Structure:
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
</div>
Jquery:
$( ".inner" ).before( "<p>Test</p>" );
Result (HTML):
<div class="container">
<h2>Greetings</h2>
<p>Test</p>
<div class="inner">Hello</div>
</div>
EDIT:
Please see sample below, it takes value from text box and insert it before
HTML Structure:
<div id="content">
<input type="text" value="textboxvalue" > <br/><br/>
<span>Insert text box value befor this one</span>
</div>
JQUERY:
var inputval = $("#content input").val();
$( "#content span" ).before( "<p>" + inputval + "</p>" );

JSFIDDLE
Option 1 - Just using jQuery:
var input = $("#theInput").val();
$("<p />") // Create a paragraph element.
.text( input ) // Set the text inside the paragraph to your input.
.insertBefore( $( "div" ) ); // Insert the paragraph before the div element(s).
Option 2 - Modifying your code:
var input = $("#theInput").val(),
content = document.createElement("p");
content.appendChild(document.createTextNode(input));
$( content ).insertBefore( $( "div" ) );
Option 2a - Or you can change the last line to:
$( "div" ).before( content );

Related

How do I add singular closing div before a element in html '</div>'

I'm generating a series of columns (HTML templates) that are generated in PHP.
The grid system is materializecss, which is Material Design.
What I want to do is to add another row s12, which is a HTML template, that takes up the entire row beneath the selected div, but first I need a close off the row which the selected column resides in, via </div>.
I tried it via innerHTML and insertAfter() but no luck.
<div class='container'>
<div class='row' >
<div class='col s6' data-index-value='2'> <!-- This column is dynamically added-->
<div class="holder-for-blah">
<p>Blah</p>
<button id='clicky'>Click to more information about</button>
</div>
</div>
</div>
</div>
// My attempts
let htmlString = "<div><p>More information section</p></div>";
newDiv = document.createElement('div');
newDiv.innerHTML = htmlString;
newDiv.innerHTML = "</div>" + htmlString
// result is undefined
$( "</div>" + newDiv ).insertAfter( "[data-index-value='2']" ) );
// after a successful response, the new html is simple not added to the DOM
//and even, adding the closing div first and then the element
$( "</div>").insertAfter( "[data-index-value='2']" ) );
$( newDiv ).insertAfter( $( "[data-index-value='2']" );
I have already tried getting the innerHTML and insertAfter.
UPDATED EDIT WITH IMAGES:
Initial grid (fine)
Starting grid
When the user clicks on the last column
It displays fine,
Last column selected
The reason why I trying to 'close off the row' is because of this issue.
When the first or second column is clicked, it gets messed up

Toggle elements view on buttons click

I have different divs which all have the same class "textBox".
At the same time there should always just be one box displayed. For most Boxes there is a button on the bottom of my page which can be clicked and triggers
to make the box visible and hide the box which is already shown at this moment.
Edit: Fiddle https://jsfiddle.net/8uvsq7ta/
For this I have this JS-code:
$( "#gettingStartedButton" ).click( function () {
if (! $( "#gettingStarted" ).is( ":visible" ) ) {
if ( $( "#extension" ).is( ":visible" ) ) {
$( "#extension" ).fadeOut( function () {
$( "#gettingStarted" ).fadeIn();
});
}
else if ( $( "#executingBox" ).is( ":visible" ) ) {
$( "#executingBox" ).fadeOut( function () {
$( "#gettingStarted" ).fadeIn();
});
}
else if ( $( "#feedback" ).is( ":visible" ) ) {
$( "#feedback" ).fadeOut( function () {
$( "#gettingStarted" ).fadeIn();
});
}
else if ( $( "#impressum" ).is( ":visible" ) ) {
$( "#impressum" ).fadeOut( function () {
$( "#gettingStarted" ).fadeIn();
});
}
else if ( $( "#registration" ).is( ":visible" ) ) {
$( "#registration" ).fadeOut( function () {
$( "#gettingStarted" ).fadeIn();
});
}
}
else {
$( "#gettingStarted" ).fadeOut( function () {
$( "#executingBox" ).fadeIn();
});
}
});
The div boxes look like this:
<div id="gettingStarted" class="textBox">
test blabla
</div>
<div id="feedback" class="textBox">
test blabla
</div>
<div id="registration" class="textBox">
test blabla
</div>
<div id="impressum" class="textBox">
test blabla
</div>
CSS:
.textBox {
diplay: none;
}
This Code checks if the box is already shown and if yes it checks EVERY OTHER BOX to get the one which is visible and then fade it out to afterwards fade the reffered box in.
My problem is, I need this part of code for every box. I think there should be a better way to accomplish this.
What I am searching is kind a method openBox(id) where I give the id of the box as paramete and it automatically detects all other boxes with the class parameter and detects which is already faded in, then fades this out to fade the box with the id in.
Sadly my javascript skills aren't that good, so I seek to find some advices or examples how to achieve this.
Thank you very much for every input you can give me.
var $textBox = $(".textBox"); // get 'em all!
$textBox.eq(0).fadeIn(); // FadeIn first one
$("[data-showid]").on("click", function(){ // Buttons click (Use data-* attribute!)
var $box = $("#"+ this.dataset.showid); // Get the target box ID element
$textBox.not($box).hide(); // Hide all bot targeted one
$box.stop().fadeToggle(); // FadeToggle target box
});
.textBox{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gettingStarted" class="textBox">getting started blabla</div>
<div id="feedback" class="textBox">feedback blabla</div>
<div id="impressum" class="textBox">impressum blabla</div>
<button data-showid="gettingStarted">GS</button>
<button data-showid="feedback">FB</button>
<button data-showid="impressum">Imp</button>
If you don't want the current box to toggle, than instead of .fadeToggle() use .fadeIn().
http://api.jquery.com/fadetoggle/
https://api.jquery.com/data/
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
With the addition of a data-* attribute on your button to link it to its content:
<button id="gettingStartedButton" data-link="gettingStarted">GS</button>
<button id="feedbackButton" data-link="feedback">FB</button>
<button id="impressumButton" data-link="impressum">Imp</button>
The javascript becomes very simple:
$( "#gettingStarted" ).fadeIn();
$('button').click(function(){
var link = $(this).data('link');
$('.textBox:visible').fadeOut(function(){
$('#' + link).fadeIn()
});
})
Updated fiddle: https://jsfiddle.net/8uvsq7ta/2/
I did it using class. The HTML would be like :
<div class="textBox gettingStartedButton" style="display: none;"> 1 test blabla </div>
<div style="display: none;" id="feedback" class="textBox .gettingStartedButton gettingStartedButton"> 2 test blabla </div>
<div id="registration" class="textBox gettingStartedButton" style="display: block;">3 test blabla </div>
<div id="impressum" class="textBox"> 4 test blabla </div>
And use the code below. Keep any element visible at first. Then on click of that element it fades it out and fades the next element in. and adds the class "gettingStartedButton" to the visible element to run click event again.
$( ".gettingStartedButton" ).on('click', function () {
var visible_element = $('.textBox:visible');
visible_element.next().fadeIn();
visible_element.next().removeClass('gettingStartedButton');
visible_element.next().addClass('gettingStartedButton');
visible_element.fadeOut();
});

Replace text in paragraph in div by clicking on a span

I am looking to change a paragraph of text into different text by clicking on a fake 'link' (span) at the bottom of the page.
what I have thus far
<body>
<p> here is a paragraph that i would like to change once the span below me is clicked </p>
<span id="click"> click me for the text above me to change </span>
</center>
</body>
<script>
$( "click" ).click(function() {
$( "p" ).replaceWith( "new paragraph" );
});
</script>
I'm really new to jquery and javascript so any help would be appreciated! thanks.
1st: for id you should use #
2nd: to get the previous element use .prev() .. $(this).prev('p')
<script>
$( "#click" ).click(function() {
$(this).prev( "p" ).replaceWith( "<p>new paragraph</p>" );
});
</script>
Note: id must be unique so don't use same id for more than one element
so try to use class instead <span class="click"> and then use $('.click') instead of $('#click')
3rd: what is </center> in your code should do?
4th: you should check to include jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
5th: put script before closing body tag
full code
<body>
<p> here is a paragraph that i would like to change once the span below me is clicked </p>
<span id="click"> click me for the text above me to change </span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(docuemt).ready(function(){
$( "#click" ).click(function() {
$(this).prev( "p" ).replaceWith( "<p>new paragraph</p>" );
});
});
</script>
</body>
to put img instead of paragraph use
$(this).prev( "p" ).replaceWith('<img src="http://placehold.it/350x150">');
to put img inside paragraph
$(this).prev( "p" ).html( 'new paragraph<img src="http://placehold.it/350x150">' );
$( "click" ) should be $( "#click" )
In reality you don't need replaceWith(). You can just use text() to change the text.
$( "#click" ).click(function() {
$( "p" ).text( "new paragraph");
});

paragraph Select() doesn't work in javascript

Here is my html code
<div id="dialog" title="Basic dialog" style="display: none">
<p id="para">Copy this key</p>
<p id="key">4567887654345678</p>
</div>
<button>Open dialog</button>
The div appears as a dialog on button click, and I would like to have the "key" text selected when the dialog opens
Here is the javascript for the same, but the < p> doesn't appear to be selected
$(function() {
$( "button" ).click(function() {
$("#dialog" ).dialog();
$( "#dialog" ).show( "slow" );
$("#key").select();
});
});
How can I make the < p> be pre-selected ?
Change the key paragraph to an editable element, such as a textarea:
<textarea id="key">4567887654345678</textarea>
JSFiddle
It appears you need an editable text field to select text in.
I think you should use jQuery dialog open event:
$( "#dialog" ).dialog({
open: function( event, ui ) {
$("#key").select();
}
});
JSFiddle

How do you push HTML into an array?

I have an array which is currently pulling through the Title of an item
This array is then used as the source of jQuery UI's autocomplete.
When typing into a HTML input, the autocomplete finds the list of Titles from the array
I would like to us the ID of the item to append to the URL when clicking search (Its currently configured to push the Title as that's what's in the Array
When pushing the ID into the array, naturally both the Title and ID are being displayed in the autocomplete drop down. However, I do not want the ID to be displayed, I simply what to extract it, based on the title so I can append it to the url.
The difficulty i'm currently having is that if I try to create a HTML structure as a variable to push into an array, the HTML is display within the HTML input box when typing.
For example:
var prodResultTite = $(this).attr('ows_Title');
var prodResultID = $(this).attr('ows_ID');
var prodResultContainer = '<div class="result" id="' + prodID + '">' + prodTitle + '</div>';
//itemTitle.push($(this).attr('ows_Title'));
itemTitle.push(prodResultContainer);
This results in the input field displaying:
'<div class="result" id="' + 125+ '">' + My Product Title + '</div>';
As you can see, the ID and Title are pulled through perfectly, however, the HTML is also dragged through.
Is there anyway for the HTML to literally be a div rather than a string in this instance?
Any help would be greatly appreciated :)
use this code but just one point you should pay attention to.
in autoComplete you should have a <a></a> tag for each suggestion or you will not be able to hover on items or select an item. because it triggered by clicking in the <a></a> tag.
HTML
<input id="search" type="text"/>
<div id="itemcontainer" style="display:none">
<div class="item" id="id_1" title="Item 1">Item1</div>
<div class="item" id="id_2" title="Item 2">Item2</div>
<div class="item" id="id_3" title="Item 3">Item3</div>
<div class="item" id="id_4" title="Item 4">Item4</div>
</div>
<input type="button" id="seeVal" value=" see autocompele html" />
CSS
.result , .result *{
color:#f00 !important;
}
.result#id_2 ,.result#id_2 *{
color:#00f !important;
}
JS
$(document).ready(function(){
/*var items = [
{
id:1,label:'lbl1'
},
{
id:2,label:'lbl2'
},
{
id:4,label:'the label3'
},
{
id:5,label:'the label4'
},
];*/
var items=[];
$('#itemcontainer').find('.item').each(function(){
items[items.length]={'id':$(this).attr('id'),'label':$(this).html()}
});
$('#search').autocomplete({
minLength: 0,
source:items,
focus: function( event, ui ) {
$('#search').val( ui.item.label );
return false;
},
select: function( event, ui ) {
$('#search').val( ui.item.label );
return false;
}
}).data( "ui-autocomplete" )._renderItem = (function( ul, item ) {
var $div=$('<div></div>').addClass('result').attr('id',item.id).html('<a>'+item.label+'</a>');
return $( "<li>" )
.append($div)
.appendTo(ul);
});
$('#seeVal').on('click',function(){
alert($('.result').parent().parent().html());
});
});
Here is updated codepen http://codepen.io/anon/pen/sjmeB
the 'seeVal' button and CSS are for testing the output

Categories

Resources