How do you push HTML into an array? - javascript

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

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

Dynamically added semanctic ui checkbox / radio / rating events not firing

Dynamically added checkbox / radio buttons / rating elements are not firing the attached events in semantic ui. Below is the js fiddle for sample and its not all triggering the events when check box is checked i have tried both 'setting' option and onChange separately as well. nothing is working as expected.
Javascript :
$("#cbdiv").checkbox('setting', 'onChange', function() {
alert("Changed");
});
$("#addcheckboxes").unbind();
var chkcounter = 0;
$("#addcheckboxes").bind('click', function() {
$('#chkgrp').append("<div id='chkbx_'" + chkcounter + "class='ui checkbox'><input type='checkbox' ></div>");
$('#chkbx_' + chkcounter).checkbox({
onChange: function() {
alert('i am added. my id is : ' + $(this).attr('id'));
}
});
});
Html
<div class="field">
<div id="cbdiv" class="ui toggle checkbox">
<input type="checkbox" id="confirm" name="confirmed">
<label>Confirmed</label>
</div>
<div>
<button id="addcheckboxes">Add checkboxes</button>
<div id="chkgrp">
</div>
</div>
</div>
Jsfiddle sample
It is because of the append statement adding wrong id element. After the append statement execute, if you look at your html it will look like below.
<div id="chkgrp">
<div id="chkbx_" 0class="ui checkbox">
<input type="checkbox">
</div>
</div>
After the above code execute, you are searching for the id chkbx_0 through jquery and try to add the onChange event for that. So it is failed. Update your append element syntax like below and it will work.
$('#chkgrp').append("<div id='chkbx_" + chkcounter + "' class='ui checkbox'><input type='checkbox' ></div>");
In the above code, I have closed id string after adding chkcounter id='chkbx_" + chkcounter + "'. In your earlier code you have closed the id string before adding the chkcounter itself id='chkbx_'" + chkcounter + ".
UPDATE
Looks like your semantic css have the following styles.
.ui.checkbox input {
position: absolute;
top: 0px;
left: 0px;
opacity: 0;
outline: 0px;
}
Because of the above styles you are not able to see the checkboxs. If you want to see the styled checkbox then you have add the label to your check box and update your code like below.
$('#chkgrp').append("<div id='chkbx_" + chkcounter + "' class='ui checkbox'><input type='checkbox'><label>test</label></div>");
Also I have noticed that you are trying to get the ID of the element using $(this).attr('id'). This statement will give the output undefined, because the checkbox does not have any attribute called id. I hope you are trying to get the id chkbx_0. In that case you have to add your code like below.
$(this).parent().attr('id');
I have updated your fiddle with all the above changes and you can see the demo here.
In checkbox code ID name is not set properly that's is the reason. You can see below working code
$("#addcheckboxes").bind('click', function() {
chkcounter++; // set counter increment
$('#chkgrp').append("<div id='chkbx_"+chkcounter+"' class='ui checkbox'><input type='checkbox' name='checkboxval[]' id='checkbox_id_"+chkcounter+"' ></div>");
$('#chkbx_'+chkcounter).checkbox({onChange:function(){alert('i am added. my id is : '+$(this).attr('id'));}});
});
Hope this will help you.

jQuery - Copy a dynamic link from one element to another

The URL in div.alpha is dynamic. I need to take this URL and apply it to an 'a href' that wraps 'View Details' in div.beta
<div class="alpha">
Example
Plus some other stuff which may contain links, etc
that I don't want to copy to the other div.
</div>
<div class="beta">
View Details
</div>
Desired result:
<div class="alpha">
Example
Plus some other stuff which may contain links, etc
that I don't want to copy to the other div.
</div>
<div class="beta">
View Details
</div>
I can get the link like this: $('.alpha').find('a').attr('href');
But I don't know how to pass that link to the XXXX below:
$('.beta').each(function(){
$(this).text($(this).text().replace('View Details', 'View Details'));
});
You could clone a.alpha, then just wrap .b's contents with it:
// clone the link, remove the text
$link = $('.alpha').find('a').clone().text('');
// wrap all .beta's contents with the cloned link
$('.beta').contents().wrap($link);
Here's a fiddle
You can achieve the result by updating your code to following.
var href = $('.alpha').find('a').attr('href'); // get href of anchor
var text = $('.beta').text(); // get text of beta element i.e. View Details
var betaHTML = "<a href='" + href + "'>" + text + "</a>"; // Create anchor
$('.beta').html(betaHTML); // Update beta element
If you have several div.alpha and div.beta elements then the best way to achieve this -- it also works for a single pair -- is:
$('div.beta').html(function(i,html) {
return $(this).prev('div.alpha').find('a').clone().html( html );
});
$('div.beta').html(function(i,html) {
return $(this).prev('div.alpha').find('a').clone().html( html );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pair">
<div class="alpha">
Example 1
</div>
<div class="beta">
View Details
</div>
</div>
<div class="pair">
<div class="alpha">
Example 2
</div>
<div class="beta">
View Details
</div>
</div>
var $betaAnchor = $('.alpha a').clone(); //clone anchor
var anchorLabel = $beta.text(); //grab text from beta tag
$('.beta').append($betaAnchor.text(anchorLabel)); //append cloned anchor with beta text
jQuery - Copy a dynamic link from one element to another
CopyLink = jQuery('.page-id-269 ').find('a').clone().attr('href');
jQuery("#menu-item-387 a").attr("href", CopyLink);
Best solution 100% Work

Append div or span to a dropdown list

I would like to "attach" a div to a dropdown list. Is that possible?
I require something like this:
To be clear, I don't need to add div into the proper dropdownlist controller. I just need to attach.
What I've tried so far and not working:
HTML:
<select id="platypusDropDown">
<option value="duckbill">duckbill</option>
<option value="duckbillPlatypus">duckbillPlatypus</option>
<option value="Platypus">Platypus</option>
<option value="Platypi">Platypi</option>
</select>
<div id="addCategory">
<input id="categoryInput" type="text" /> <br/>
<input id="categoryInputAddBtn" type="button" value="Add new" />
</div>
JS:
$('#platypusDropDown').click(function () {
var myDiv = document.getElementById('addCategory');
this.append(myDiv);
});
Any solution? Thanks in advance.
I don't think so, what you are trying to achieve is possible using select dropdown.What here, i will do is modify my HTML Code and use css style.
<style type="text/css">
ul{ list-style: none;
margin: 0;
padding: 0; }
</style>
Here is my HTML Code: Instead of dropdown, i am using here ul li listing element.
<div class="select-wrapper">
Select Dropdown
<ul id="platypusDropDown" style="display:none;">
<li rel="duckbill">duckbill</li>
<li rel="duckbillPlatypus">duckbillPlatypus</li>
<li rel="Platypus">Platypus</li>
<li rel="Platypi">Platypi</li>
</ul>
</div>
<div class="wrapper" style="display:none;">
<div id="addCategory">
<input id="categoryInput" type="text" /> <br/>
<input id="categoryInputAddBtn" type="button" value="Add new" />
</div>
</div>
Here is my JS code:
<script type="text/javascript">
$(document).ready(function(){
var flg = 0;
$('.select-wrapper').click(function(){
flg++;
if(flg == 1){
$this_html = jQuery('.wrapper').html();
$("#platypusDropDown").append("<li>"+$this_html+"</li>");
}
$("#platypusDropDown").slideToggle();
});
});
</script>
You can't add DIV to selectBlock. But you can add option into select:
$('#platypusDropDown').click(function () {
var myDiv = document.getElementById('addCategory');
$(this).after(myDiv);
});
LEAVE jQuery Part . This is not possible by setting HTML static markup WITH select Containing DIV . SO IT IS NOT POSSIBLE . u may use markup but , still It wil hide in browser even though u can see in Firebug , div is attached to dropdown.
But if u r asking for : add Text as option in dropdown , then ,
Working FIDDLE
$('#categoryInputAddBtn').click(function () {
var myDiv = $('#categoryInput').val();
//this.append(myDiv);
var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text(myDiv);
$('#platypusDropDown').append(option);
});
As far as I know this is not possible with standard HTML select/option tags. But there are several different libraries emulating dropdown functionality and giving additional functionalities. One of those is UI Kit which provides this among a lot of other features. You can add so called 'Grid' components to the dropdown which can in fact contain anything you want. See detail over here under the headline 'Grid'.
You can add input value to dropdown list.
var $platypusDropDown = $('#platypusDropDown');
$('#categoryInputAddBtn').on('click', function() {
// Value of div input
var $category = $('#categoryInput').val();
// Add to dropdown list
$platypusDropDown.append('<option value="' + $category + '">' + $category + '</option>');
});
Why you whant add div to Options? You could try like this:
$('#platypusDropDown').click(function () {
var dropHeight = $(this.options[0]).height() * this.options.length;
if($(this).data('open')) {
$(this).data('open', false);
$('#addCategory').css('padding-top', '0px')
return;
}
$('#addCategory').css('padding-top', dropHeight + 'px')
$(this).data('open', true);
});
JSFIDDLE DEMO

Jquery dynamic creating HTML divs on click

I’m looking for some direction for my problem.
I’ve HTML divs and I want to replicate it when user clicks on span with id plus-1.
This is my html
<div id = “tab”>
<div class="row">
<div>
<select id="ProjectsFolder0FolderId" name="data[ProjectsFolder][0][folder_id]">
<option value="1">Project Presentation</option>
<option selected="selected" value="4">Project Root</option>
</select>
</div>
<div>
<div>
<input type="text" required="required" id="ProjectsFolder0Linux" value="xyz" name="data[ProjectsFolder][0][linux]">
</div>
</div>
<div id="plus-1" >
<span>
Click here
</span>
</div>
</div>
</div>
Jquery
$(document).on('click', '#plus-1' , function() {
var html = "<div class=\"row\" >"
???
+ "</div>";
$('#tab').append(html);
});
It is appending above html defined in jquery , but I don’t know how to append entire HTML efficiently as required above on each click.
Demo FIDDLE
Jquery
$(document).on('click', '#plus-1' , function() {
var html = $(this).parent().clone();
html.find('#plus-1').attr('id','plus-'+($('#tab').find('.row').length+1));
$('#tab').append(html);
});
Made a jsfiddle for you - http://jsfiddle.net/23GCn/. You also have an error in your html, you need to use correct parenthesis on <div id="tab">
jQuery(function($){
var count = 1;
$(document).on("click", "[id^='plus']", function(){
newBlock = $(this).parents(".row").clone();
count += 1;
// change id of Plus button
newBlock.find("[id^='plus']").attr("id", "plus-"+count);
// Change id and name of select box
newBlock.find("select")
.attr("id", "ProjectsFolder"+count+"FolderId")
.attr("name", "data[ProjectsFolder]["+count+"][folder_id]");
// Same for input
newBlock.find("input[type='text']")
.attr("id", "ProjectsFolder"+count+"Linux")
.attr("name", "data[ProjectsFolder]["+count+"][linux]");
// append new element to your tab
$("#tab").append(newBlock);
});
});
Note that [id^='plus'] type selectors are very inefficient, means, slow. Consider using classes instead of ids, this way you avoid all of the code required to change ids, since you can't have elements with same id on your page obviously.

Categories

Resources