I want to make a input field where I can search for friends in a list, these friends I retrieve from a xml file and I generate them using javascript
The code I generate this with:
friendListInDiv = document.createElement("p");
var link = document.createElement("a");
link.onclick = function() {
openChat(friendsXML[i].textContent)
};
var friendText = document
.createTextNode(friendsXML[i].textContent + ":"
+ statusXML[i].textContent);
link.appendChild(friendText);
friendListInDiv.appendChild(link);
friendDiv.appendChild(friendListInDiv);
Now the problem I'm facing I have demonstrated in a jsfiddle:
https://jsfiddle.net/x897pv9o/
As you can see if you type in "j" in the top input bar it hides all friends but type "j" in the bottom one it will still display "Joske"
This is because these tags
<div id="friendlist"><p><a>
Joske:
Offline</a></p><p><a>
Tom:
Offline</a></p><p><a>
Dirk:
Offline</a></p></div>
are not being formatted correctly, how can I make them format correctly?
As Shaunak D mentioned in a comment, you can use .trim() to remove preceding and trailing whitespace, including new lines, from text. You can either use this on your text content when creating the node, or use it in your search function to exclude new lines.
In document.createTextNode:
var friendText = document.createTextNode(
friendsXML[i].textContent.trim() + ":" + statusXML[i].textContent);
In $('#searchinfriend').keyup:
$('#searchinfriend').keyup(function () {
var valThis = $(this).val().toLowerCase();
$('#friendlist p a').each(function () {
var text = $(this).text().trim().toLowerCase();
(text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();
});
});
Related
I'm attempting to make a dynamic filter on one iframe with two input boxes. Let's call the input boxes "Box 1" and "Box 2". When both boxes are not populated, I would like the iframe to display all of the information. When Box A is populated, I want it to display information on Box A. When Box B is populated as well, I would like both the filters to apply. When only Box B is populated, I would like the iframe to only display Box B's input.
One limitation I have is the changing nature of having one of the input boxes blank. I am limited to assigning a number to the input on the URL (e.g. - col1, op1, val1). If the "salModBox" is blank for instance, it needs to be dynamic enough to assign "serNumPrefBox" with col1, op1, val1). If both are populated, it would need to be col1, op1, val1 for "salModBox" and col2, op2, val2 for "serNumPrefBox". If neither are populated, well, it doesn't need to have col1 or 2 for that matter.
Expected output of the URL would ultimately look like this if both are populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod+"&col2=Variable%20Number%20Two&op2=EQ&val2="+serNoPre+"#/moreinfo/anotherID
Expected output of the URL with one variable populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod (or serNoPre) +"#/moreinfo/anotherID
With both of them blank, it would simply be the original URL source link. This would be a wide open search. A user isn't technically limited to values they can put in either input box.
function salModSnpFilter() {
var salModInput = document.getElementById('salModBox').value;
var serNumPrefInput = document.getElementById('serNumPrefBox').value;
var smSnp = '';
if (salModInput = ' ' and serNumPrefInput = ' ') {"https://en.wikipedia.org/wiki/IFrame"
} else if (salModInput = ' ' and serNumPrefInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput
} else if (serNumPrefInput = ' ' and salModInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + salModInput
} else if (salModInput != ' ' and serNumPrefInput != ' ' {"chttps://en.wikipedia.org/wiki/IFrame"+salModInput+serNumPrefInput
} else {"https://en.wikipedia.org/wiki/IFrame"
}
var salModString = "https://en.wikipedia.org/wiki/IFrame" + salModInput";
var serNumPrefString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput";
var bothString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput + salModInput";
document.getElementById('SM_SNPiFrame').src = salModString;
document.getElementById('SM_SNPiFrame').src = serNumPrefString;
document.getElementById('SM_SNPiFrame').src = bothString;
}
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name = "Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame"
width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
I ultimately used this code and it worked:
function filterSelection() {
var smBoxValue = document.getElementById("salModBox").value;
var snpBoxValue = document.getElementById("serNumPrefBox").value;
if (smBoxValue != "" && snpBoxValue != "") {var combinedModString =
"https://example.com/col1=Serial%20Number%20Prefix&op1=EQ&val1=" +
snpBoxValue +"&col2=Sales%20Model%20BOM%20EDS&op2=EQ&val2=" +
smBoxValue";
document.getElementById('SM_SNPiFrame').src = combinedModString;
}
else if (smBoxValue == "" && snpBoxValue != "") {var snpModString =
"https://example.com/#/col1=Serial%20Number%20Prefix&op1=EQ&val1="
+ snpBoxValue;
document.getElementById('SM_SNPiFrame').src = snpModString;
}
else if (smBoxValue != "" && snpBoxValue == "") {var salModString =
"https://example/col1=Sales%20Model%20BOM%20EDS&op1=EQ&val1=" +
smBoxValue;
document.getElementById('SM_SNPiFrame').src = salModString;
}
else {document.getElementById('SM_SNPiFrame').src =
"https://example.com/";
}
}
Your code seems a bit complex than what your issue is, I'll explain to you how to correct this and use some good practices in JavaScript.
Since you need to handle the values inside the input tags and use them into the iFrame tag, we will do the following:
Global elements first.
Since we will probably need to define only once which DOM element is the iFrame tag and which ones are the input tags, lets have them at the very beginning:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
Also, we define a strings variable that will help us store the input values in the same index as elements array.
Set event listeners for every element.
After defining which elements we want to use, now we should handle the change of its value. The most fast-looking effect is to use keyup event, this will pass the value everytime that the user types:
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
In this event listener, you need to setup what will happen every time this event is fired. I just did a simple function to store the new value into the same index but in different array (strings array).
And after that done, call the function that will update the iFrame tag.
Keep your code simple and functional.
The function salModSnpFilter() doesn't need a lot of if statements and the same string appearing multiple times to handle the new source of the iFrame. Lets keep code simple:
const salModSnpFilter = () => {
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/"; //You can set it to empty: "" if you dont want slashes.
strings.forEach(string => {
if (string !== "") {
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
We define the base URL in a variable at the top and a variable that will hold the string that we will append to the base source.
We iterate over the strings array and add this string to finalString array in the same order of the inputs.
After this, the only thing left to do is to set the source of the iFrame tag.
Final code:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
const salModSnpFilter = () =>{
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/";//You can set it to empty: "" if you dont want slashes.
strings.forEach(string=>{
if(string !== ""){
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name="Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame" width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
Note: The order of the strings and how they are used on the iFrame are the same as the order you added the inputs to the elements array. This means, inputA value will always go before inputB value. Unless you change the order in the elements array.
I have a variable that contains HTML.
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';
I am trying to loop around all of the elements and replace with spans specific date. So any spans with a class of variable-source will need to be replaced with specific date, and the same for input-source.
I have tried to use the following:
$('span', html).replaceWith(function () {
var id = $(this).attr('id');
// this returns the correct id
//calculations go here
var value = 'testing';
return value
});
Which outputs the following:
testing This is a variable
All of the paragraph tags have been removed, and it seems to stop after the first paragraph. Is there something that I am missing here? I can post more code or explain more if needed.
Thanks in advance.
You need to create a html object reference, else you won't get a reference to the updated content. Then get the update content from the created jQuery object after doing the replace operations
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
'<p>Testing</p>';
var $html = $('<div></div>', {
html: html
});
$html.find('span.variable-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced variable for: ' + id;
return value
});
$html.find('span.input-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced input for: ' + id;
return value
});
var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));
I'm using jquery, as well as the CSVtoTable (plugin here: https://code.google.com/p/jquerycsvtotable/ ) plugin to convert large CSV files into tables that I can manipulate. I need to attach links relevant to each row.
I need to convert the text in one of these rows to add a link to a pdf. The problem is I can't seem to modify the strings. I'm using data like that found here: http://jsfiddle.net/bstrunk/vaCuY/297/
The file names generated by my system can't be easily edited, so I'm stuck using these formats:
423-1.pdf
So I need to convert two strings from tables formatted like so:
4/23/2013
1
to drop the year, as well as the slashes, and add a '-' and then the extra digit.
I'm able to grab the table data, I just can't seem to manipulate the variables with either the .replace or .substr
$(document).ready(function () {
$("tr td:nth-child(5)").each(function () {
var $docket = $('td=eq(5)');
var $td = $(this);
var $dataDate = $td.substr(0, $td.lastIndexOf("/"));
var $newDataDate = $dataDate.replace("/", "");
$td.html('<a html="./docs/' + $newDataDate.text() + '-' + $docket.text() + '.pdf">' + $td.text() + '</a>');
});
});
(edit): Sample table data:
<tr><td>13CI401111</td><td>22</td><td>Name1</td><td>Name2</td><td>4/23/2013</td><td>1</td></tr>
<tr><td>13CI401112</td><td>22</td><td>Name1</td><td>Name2</td><td>4/24/2013</td><td>2</td></tr>
First set the table id properly:
<table id="CSVTable">
Then use the right selector to select the 5th cell in each row:
$("#CSVTable tr td:nth-child(5)") //note that we need to tell Jquery to look for the cells inside `CSVTable` otherwise it will search the whole document
dollar sign is not required at the beginning of each variable and doesn't have any significance, you can remove it.
This wont work:
var $docket = $('td=eq(5)');
it's telling jquery to look for 6th cell but where? you should specify the parent like:
$("#CSVTable tr td:nth-child(6)");
but we only need the next cell to the one already selected in each function, so a better approach would be to use next() method which will select the next td directly:
$(this).next('td');
complete code:
$(document).ready(function () {
$("#CSVTable tr td:nth-child(5)").each(function () {
var td = $(this),
docket = td.next('td').text(),
dataDate = td.text(),
newDate = dataDate.substr(0, dataDate.lastIndexOf('/')).replace("/", '');
td.html('' + dataDate + '');
});
});
Demo
Bstrunk, try this :
$(function() {
$("tr").each(function () {
var $tr = $(this);
var $td_date = $tr.find('td').eq(4);
var $td_docket = $tr.find('td').eq(5);
var dateArr = $td_date.text().split("/");
$td_date.html('<a html="./docs/' + dateArr[0] + dateArr[1] + '-' + $td_docket.text() + '.pdf">' + $td_date.text() + '</a>');
});
});
I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.