How not to remove words after space? - javascript

Here while displaying the variable on modal upon clicking on the button I got some issue. var name = details[i].name it gives the exact full value but when I display this data on modal it only displays the first word. The words after the first word or space all removing automatically. What's wrong here with my code ?
if (details[i].taskmaster_id && details[i].events.length) {
var name = details[i].name
var status = details[i].status
console.log('status', status)
console.log(name) //displays full word here
messageCleaner.innerHTML = '<button class="btn btn-msg-cleaner btn-sm" id="msg" data-name=' + name + ' data-status=' + status + '>Message to Cleaner</button>';
//appending Message to Cleaner button
headerContentJustify.appendChild(messageCleaner);
}
$(document).on('click', '#msg', function (e) {
const {
name,
status
} = e.target.dataset;
$("#sendmessagetocleaner").modal('show')
$('#sendmessagetocleaner').on('shown.bs.modal', function (e) {
console.log(name) // displays only first word here
//if the word is john doe I only john here
$("#cleaner_name").val(name)
$("#sub").val(`${name}`)
})
});

You are missing the double quote:
messageCleaner.innerHTML='<button class="btn btn-msg-cleaner btn-sm" id="msg"
data-name="'+name+'" data-status="'+status+"
'>Message to Cleaner
</button>';
Without it, the value of the attribute is not grouped, but it's only the first word until the space. The second word is another attribute in itself.

Related

Dynamic Filter of Iframe with Two Input Fields

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.

Javascript: How to append <textarea> rows

I have a <textarea> that I am attempting to add quotation marks around each value a user puts inside the text box upon clicking a button. My code appears to be viewing every row as 1 large value and just adds quotation marks at the beginning of the first word and end of the last word where it looks like this:
"one word
two word
three word"
I am attempting to achieve this output:
"one word"
"two word"
"three word"
Here's my current code:
document.getElementById("phraseButton").addEventListener('click', function () {
var keywordBox = document.getElementById('keywordBox');
keywordBox.value = ('"' + keywordBox.value + '"');
});
<textarea id="keywordBox" type="text" rows="100" cols="30">Insert Keywords</textarea>
<button id="phraseButton">Phrase</button>
you can replace all \n in your textarea with "\n" using replace(). something like this:
document.getElementById("phraseButton").addEventListener('click', function () {
var keywordBox = document.getElementById('keywordBox');
keywordBox.value = ('"' + keywordBox.value + '"');
keywordBox.value = keywordBox.value.replace(/\n/g, '"\n"')
});
<textarea id="keywordBox" type="text" rows="100" cols="30">Insert Keywords</textarea>
<button id="phraseButton">Phrase</button>

jQuery Unable to remove multiple neighboring elements on AJAX Success

I am trying to figure out why I am unable to remove multiple neighboring elements on a successful ajax DELETE. When I had $(".file-preview").filter("a[href='" + fileLink + "']").remove(); by itself in the code below, I was able to remove the first link and when I add $(".remove-file").data("file-link", fileLink).remove(); after it, it breaks the first .remove() statement and removes all of the present .remove-file disregarding the value being passed to the data-file-link attribute in the link.
1) Why would the first remove be broken by this second remove?
2) Is there a better approach to what I'm trying to achieve which is to remove both neighboring elements on the click of .remove-file?
Here is an example of what the HTML looks like:
<div class="file-section>
<div class=" file-preview ">
https://test-bucket.s3.amazonaws.com/1/2017-01-30/screen-shot-2017-01-08-at-12.23.39-pm.png
<span class="glyphicon glyphicon-remove "></span>
</div>
<div class=" file-preview ">
https://test-bucket.s3.amazonaws.com/1/2017-01-30/screen-shot-2017-01-08-at-12.23.39-pm.png
<span class="glyphicon glyphicon-remove "></span>
</div>
</div>
jQuery:
$(document).on('click', '.remove-file', function(){
console.log('Delete Triggered');
var fileLink = $(this).data('file-link');
function pathExtract(url){
var fullUrl = url;
var delimiter = '/';
var start = 3;
var tokens = fullUrl.split(delimiter).slice(start);
var path = tokens.join(delimiter);
return path;
}
$.ajax({
url: '/app/sign?' + $.param({"file": pathExtract(fileLink)}),
type: 'DELETE',
success: function(){
console.log('This is the file link ' + fileLink);
$(".file-preview").filter("a[href='" + fileLink + "']").remove();
$(".remove-file").data("file-link", fileLink).remove();
},
error: function(error){
console.log('error ' + JSON.stringify(error));
}
});
});
.data("file-link", fileLink) isn't a filter, it sets the data of the elements selected. It simply returns the same collection it was called on, so when you call .remove() on the result it removes all the elements with the remove-file class.
If you want to remove just the elements with that data value, use .filter():
$(".remove-file").filter(function() {
return $(this).data("file-link") == fileLink;
}).remove();
This code:
$(".file-preview").filter("a[href='" + fileLink + "']").remove();
doesn't work because the a element is inside the .file-preview DIV, but .filter() tests if the element itself matches the filter. You should write:
$(".file-preview:has(a[href='" + fileLink + "'])").remove();
to test the contents.

Loop around HTML variable and replace spans with content

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>

Edit button for each DataTable row, can't pass data

I have a DataTable called Branches which has three columns: Name, Code and Email (along with an ID column hidden to users). It originally has an Edit button on top, and only after clicking on a row can the user click on the button to open a dialog box with the fields populated and edit them. Now however I need to change it so that each row has its own Edit button, therefore removing the need to click on the row first.
So now I have an Edit button for each row in a DataTable, but I can't pass the data for that particular row besides the Index number. The relevant blocks of code are below (unless I missed something, please tell me if I have):
var txtName2 = $("#txtName2"); //For Update
var txtCode2 = $("#txtCode2");
var txtEmail2 = $("#txtEmail2");
var dialog;
var tblBranch = $("#tblBranches");
var branchList;
var selectedIndex;
branchList = response.branches;
var data = { "aaData": [] };
$.each(response.branches, function (i, item) {
data.aaData.push({
"id": item.id,
"name": item.name,
"code": item.code,
"email": item.email,
"action": "<button> class='btnUpdate' type='button' onClick='testUpdateButton(" + i + ")'</button>"
});
});
function testUpdateButton(index, name, code, email) {
//alert(index);
selectedIndex = tblBranch.row(this).index();
var selectedName = tblBranch.row(index).name;
var selectedCode = tblBranch.row(index).code;
var selectedEmail = tblBranch.row(index).email;
//alert(name);
onBtnUpdateClicked(index, name, code, email);
}
function onBtnUpdateClicked(index, name, code, email) {
if (branchList != null && branchList.length > 0) {
var selectedItem = branchList[selectedIndex];
txtName2.val(selectedItem.name);
txtCode2.val(selectedItem.code);
txtEmail2.val(selectedItem.email);
dialog = $("#dialog-form-update").dialog("open");
}
}
When I only pass in the index number 'i' at the button and not the name, code or email, the alert(index) under testUpdateButton displays the correct index number of the selected row, therefore confirming it can get the index number, but not the other three columns (the alert(name) displays nothing).
So I've tried passing all four fields at the button like such:
"action": "<button> class='btnUpdate' type='button' onClick='testUpdateButton(" + i + ", " + item.name + ", " + item.code + ", " + item.email + ")'</button>"
but it only gives me an error: "Uncaught SyntaxError: missing ) after argument list" when I inspect the page in Chrome. I can't see where the missing bracket should be.
Basically, I can obtain the index number but cannot use it to get the corresponding name, code and email.
For reference, here is the function that's the closest thing to a solution I had earlier - this would pass all the row data and load the Editing dialog box with the input fields populated whenever I clicked anywhere on the row itself. It was modified from the previous "Click on row first" version, though I merely added the onBtnUpdateClicked function. Not ideal, but at least it did what it should.
$("#tblBranches tbody").on('click', 'tr', function () {
selectedIndex = tblBranch.row(this).index();
onBtnUpdateClicked();
});
Any help is much appreciated.
Since you are able to get the index of row, you can use this to get other values. Try something like this
function testUpdateButton(index){
//alert(index);
selectedIndex = index;
var name=$("table tr").eq(index).children('td').eq(1).text();
var email=$("table tr").eq(index).children('td').eq(2).text();
alert(name);
alert(email);
onBtnUpdateClicked(index, name, email);
}
A woorking fiddle to get these values is https://jsfiddle.net/shoaibakhter/atpgdofh/19/. This is not a complete solution, but yes this will help you to get other values, which you can pass in your onBtnUpdateClicked function. You have to change the functions as per your table structure and in your onBtnUpdateClicked use these values as below-
function onBtnUpdateClicked(index, name, email) {
if (branchList != null && branchList.length > 0) {
var selectedItem = branchList[index];
txtName2.val(name);
txtEmail2.val(email);
dialog = $("#dialog-form-update").dialog("open");
}
}
Hope this will help you.

Categories

Resources