Removing option_for_select item with variable name in Javascript - javascript

I have this piece of code:
function remove_name(i) {
var phase_name = document.getElementById('phase_rates_phase_name' + '-c' + i).value;
$("select#payer_contract option[value='Phase 3']").remove();
}
This correctly removes the item from the dropdown if it is Phase 3, but I want to remove the variable. Is there a way of doing something like
$("select#payer_contract option[value='phase_name']").remove();
?

$("select#payer_contract option[value='" + phase_name + "']").remove();

Related

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

hyperlink alternate text replacement

At the moment i've got this code, which replaces a span class whith a hyperlink. The hyperlink includes a abbreviation and the alternate texxt for the hyperlink includes the same abbreviation. Now what i want to do is, to somehow replace the second abbreviation in the alternate text of the hyperlink. So that there isn't "click here to visit + 'name of'abbreviation" but instead an alias. So if the abbreviaton is ggl, the alias should be google. But the hyperlink shouldn't use this alias. Can sb help me? thx
(function($) {
var number = "1234567";
function linkBuilder(abbreviation) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation + "</a>";
}
function linkBuilder2(abbreviation2) {
return "<a href='https://www.test.com/" + abbreviation2 + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation2 + "</a>";
}
jQuery(document).ready(function() {
var fl = $(".first-link");
if (fl.length > 0) {
fl.html(linkBuilder(fl.data("abbreviation")));
}
var sl = $(".second-link");
if (sl.length > 0) {
sl.html(linkBuilder2(sl.data("abbreviation2")));
}
});
})(jQuery);
Here is a working jsfiddle:
https://jsfiddle.net/e7qdx031/1/
linkBuilder() should be re-usable, as kalsowerus mentioned.
Another thing that should be mentioned is that the following code returns a collection of elements, not just a single element.
var fl = $(".first-link");
...
var sl = $(".second-link");
The code you have provided will not function properly if there are multiple .first-link classes on the page. So instead I would iterate over each element using $.each() and run the linkBuilder() function on them individually.
As for the linkBuilder function I would modify it to accept the element object, then read the properties to retrieve alias and name. Full name is something that you seemed to indicate you need, but was not present in the code.
(function($) {
var number = "123456";
function linkBuilder($obj) {
var abbreviation = $obj.data('abbreviation');
var name = $obj.data('name');
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + name + "</a>";
}
jQuery(document).ready(function() {
$('.first-link, .second-link').each(function(index, obj){
$(obj).html(linkBuilder($(obj)));
});
});
})(jQuery);
What you probably want is something like this:
function linkBuilder(abbreviation, alias) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + alias + "</a>";
}
Just pass the display-name you want for your link as the second argument.

jQuery getJSON and get value from button

I'm download data from JSON file and display button with value:
function iterateOverPrzepisy(best) {
$('#listaPrzepisow').html('');
$.getJSON('przepisy.json', function(data) {
for (var x in przepisyDost) {
$('#listaPrzepisow').append(" <div data-role=\"collapsible\"><h2>" + przepisyDost[x].nazwa + "</h2>" +
"<ul data-role=\"listview\" data-theme=\"d\" data-divider-theme=\"d\">" +
"<li>" +
"<h3>Składniki: " + przepisyDost[x].skladniki + "</h3>" +
"<p class='ui-li-desc' style='white-space: pre-wrap; text-align: justify;'>" + przepisyDost[x].tresc + "</p>" +
"<button id='ulubioneBtn' value='" + przepisyDost[x].id + "'>Ulubione</button></li>" +
"</ul>" +
"</div>");
j++;
}
})
}
When I click to button #ulubioneBtn I would like to get value from this button. So I add done to getJSON
}).done(function(data){
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $("button#ulubioneBtn").val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
});
But it's not working. When I click on button Ulubione I always get in console log value = 0
The problem seems to be that you add multiple buttons with the same id. An id of a html element should be unique.
przepisyDost does not appear to be defined at
for (var x in przepisyDost) {
? Try
for (var x in data.przepisyDost) {
Duplicate id's are appended to document at
"<button id='ulubioneBtn' value='" + przepisyDost[x].id
+ "'>Ulubione</button></li>" +
within for loop. Try substituting class for id when appending html string to document
"<button class='ulubioneBtn' value='" + data.przepisyDost[x].id
+ "'>Ulubione</button></li>" +
You could use event delegation to attach click event to .ulubioneBtn elements, outside of .done()
$("#listaPrzepisow").on("click", ".ulubioneBtn", function() {
// do stuff
})
I have created a dummy JSON and executed the same JS with a single change.
In onclick handler instead of getting button I am using $(event.target).
And it is working fine.
Please find the fiddle https://jsfiddle.net/85sctcn9/
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $(event.target).val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
Seems like first object doesn't have any id value.
Please check JSON response returned from server.
Hope this helps you in solving.

Not able to Add more text in text area

I'm trying to add text in a textarea. I think I'm missing some ....my code is below:
$.each(result, function (i, v) {
if (ui.item.value === v.TextKeyword) {
if ($('input:radio[name="' + currentid + '"]:checked').val() == 'Append') {
var cannedtext = $("textarea[parentcontrolid='" + currentid + "']").text() + "," + v.Text;
$("textarea[parentcontrolid='" + currentid + "']").text(String(cannedtext));
} else {
$("textarea[parentcontrolid='" + currentid + "']").text(v.Text);
}
$("textarea[parentcontrolid='" + currentid + "']").focus();
}
});
but when I execute the code it displays this:
You have to use .val() instead of .text().
According to Jquery:
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method.

Javascript add event listener in a foreach loop only last entry works

I have a function which goes through an Array and adds <h3> elements to a div. Then it adds an event listener (an onclick) to the current <h3> element, but only the last element which goes through the function is set by the onclick.
var runstr = [];
//txt comes from the content of a tab separated textfile spilt by '\n'
txt.forEach(function (lcb) { //lcb goes through each line of txt
lcb = lcb.split(" ", 30); //split the line by tab
//MainContent_Infralist is a div where the <h3> elements are listed and lcb[2] is the title
document.getElementById("MainContent_Infralist").innerHTML =
document.getElementById("MainContent_Infralist").innerHTML +
'<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';
//I put the id into an array to get the index of the marker later
runstr.push("Infralist_" + lcb[2]);
//I'm working with openlayers here i try to set the entry of
//the list.onlick to trigger a mousedown on a marker.
//And there is the problem: It works, but only for the last entry of my <h3> list...
document.getElementById("Infralist_" + lcb[2]).onclick = function () {
var theM = runstr.indexOf("Infralist_" + lcb[2]);
markers.markers[theM].events.triggerEvent('mousedown');
};
};
The problem is here:
document.getElementById("MainContent_Infralist").innerHTML =
document.getElementById("MainContent_Infralist").innerHTML +
'<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';
Every time you assign to innerHTML, you're basically deleting all stuff and adding it all over again. This causes all event listeners to break.
That's the reason why only last one works - it's the only one after assigning which there is no more innerHTML manipulation.
To fix this, create your elements using document.createElement() and append them using element.appendChild().
It could look like:
var header = document.createElement('h3');
header.id = 'Infralist_' + lcb[2];
header.className = 'Infraa';
header.textContent = lcb[2];
document.getElementById('MainContent_Infralist').appendChild(header);
header.onclick = function () {
// you function here
}

Categories