Change a button label using Javascript - javascript

I have a submit button which I am sharing between 'Create' and 'Update'. I want the following labels depending on my page state:
Create = Submit
Update = Update
These buttons also have an image at the front of them using glyphicon but the image will be the same for both buttons.
To get to my page states (listed above) I have other JavaScript functions which the relevant buttons call.
All my code is below. I am struggling as I am fairly new to JavaScript and I now I can do it by adding using Value but this doesn't work due to my image.
Edit Button HTML
<button type="button"class="btn btn-default" name="RegCashMove_Edit_Button" onclick='RegCashMoveEdit()'>
<span class="glyphicon glyphicon-pencil" title="Edit" style="vertical-align: middle"></span>
</button>
Create Button HTML
<button type="button" class="btn btn-default" name="RegCashMove_Create_Button" onclick='RegCashMoveCreate()'>
<span class="glyphicon glyphicon-plus"></span> Create
</button>
Variable Button HTML
This is the button I want the label to be variable on. At the moment its 'Submit'
<button name="RegularCashMovements_Submit_Button" class="btn btn-default" id="RegularCashMovements_Submit_Button" type="submit">
<span class="glyphicon glyphicon-ok"></span> Submit
</button>
JavaScript function for 'Create' button
function RegCashMoveCreate(txt) {
document.getElementById('selection').value = "Create";
document.getElementById('index').value = "";
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_To_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_Amount_TextBox').value = "";
document.getElementById('RegCashMove_Frequency_DropDownList').value = "0";
};
JavaScript function for 'Edit' button
function RegCashMoveEdit(txt, from, to, amount, frequency, index) {
document.getElementById('selection').value = "Edit"
document.getElementById('index').value = index;
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = from;
document.getElementById('RegCashMove_To_DropDownList').value = to;
document.getElementById('RegCashMove_Amount_TextBox').value = amount;
document.getElementById('RegCashMove_Frequency_DropDownList').value = frequency;
};
I no I should be able to add a variable in each of my JavaScript function to display the relevant label but my issue is getting it on the button with my image

You can set the textual content of a HTML element with the "textContent" property ("innerText" in IE < 9):
var button = document.getElementById('RegularCashMovements');
button.innerText = button.textContent = 'new text';
The span element inside the button element should not be removed.
If you also want to change the title of the span do it like that:
for (var index = 0; index < button.childNodes.length; index++) {
if (button.childNodes[index].tagName == 'SPAN') {
button.childNodes[index].title = 'new title';
break;
}
}
You need to iterate through all child nodes of the button, instead of taking the first one, because than you will get the text content of the button again.
I hope i understood your problem. I also have to say, that your javascript is very procedural and inperformant because of all the "display: none;" and innerHTML accesses. My tip for you would be to think more objective and put all elements you need to hide in one container element and hide that one.

Related

How to loop over dynamically generated input fields?

I am generating some input fields dynamically on my page, and I want to grab inputs from them to store in localStorage if this way works if not? suggest a way around, how can this be done? also how can i add a event listener to submit button ? followings are code have a look at it and give some suggestions/improvisations.
..
HTML
<div id="warnMessage"></div>
<div class="add"></div>
<div class="inputs">
<input
type="text"
maxlength="1"
id="inputValue"
/>
<button class="btn" type="button">+</button>
</div>
javascript
const div = document.querySelector(".add");
const add = document
.querySelector(".btn")
.addEventListener("click", addingInps);
function addingInps() {
const inputValue = parseInt(document.getElementById("inputValue").value);
if (isNaN(inputValue)) {
document.getElementById("warnMessage").innerText = "Enter Again";
document.getElementById("inputValue").value = "";
} else {
const form = document.createElement("form");
form.method = "post";
form.action = "#";
for (let i = 0; i < inputValue; i++) {
const inp = document.createElement("input");
inp.type = "text";
inp.maxLength = "12";
inp.required = true;
inp.className = "inp";
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(inp);
form.appendChild(br.cloneNode());
div.appendChild(form);
document.querySelector("#inputValue").style.display = "none";
}
const sub = document.createElement("button");
sub.className = "subButton";
sub.type = "button";
sub.value = "button";
sub.textContent = "Submit"
form.appendChild(sub);
}
}
You are loop through an input ...not an array or nodelist.
It cant work
I think it would be easier if you appended an ID with every new input field you made
for(let i=0;i < inputValue;i++){
// create your element ipt
ipt.setAttribute("id","autogenerated_" + i);
}
and grab value based on id
document.getElementById("autogenerated_x").value();
about setting an event listener, I can't think any other way of the classic
btn.addEventListener("click", function(e){
// your functionality
});

How do i create a system where a user can favourite/unfavourite individual courses on a webpage?

I am trying to create a 'favourites' system where the user can click on a star in the top right of a button to add that course to their list of 'favourites'. Here is the HTML for said button (there are 6 of them and all 6 are the same):
<button class="divflexbuttonitem">
<div class="libraryfaviconcontainer">
<i class="libraryfavicon" onclick="toggleFavourite()"></i>
</div>
</button>
And here is my (attempt at) JavaScript for the toggleFavourite() function:
function toggleFavourite() {
console.log("Running toggleFavourite();");
var favicon = document.getElementsByClassName("libraryfavicon");
var faviconCount = favicon.length;
var favArray = new Array();
var favArrayString = favArray.toString();
var i;
for(i = 0; i < faviconCount; i++) {
favArray.push(favicon[i].id);
}
alert(favArray.length);
alert(favArrayString);
let favourite = false;
if (favicon[i].style.backgroundImage == 'url("libraryfavselected.png")') {
favourite = true;
}
else if (favicon[i].style.backgroundImage == 'url("libraryfavunselected.png")') {
favourite = false;
}
if (!favourite) {
favicon[i].style.backgroundImage = 'url("libraryfavselected.png")';
console.log("Added to Favourites");
}
else {
favicon[i].style.backgroundImage = 'url("libraryfavunselected.png")';
console.log("Removed from Favourites");
}
}
I am trying to get all elements with a specific class name, add them to an array, and call them from an array to change the url of the 'favicon' of the specific favicon that was pressed. However, my code does not work whatsoever and i am lost as to how to correctly code it.
There are better ways to structure this type of application, but here is some really simple code to get you started.
You can see that the fav class is toggled on and off when an item is clicked, and then we can get all the current favourites by querying all elements with the fav class.
const toggleFavourite = (event) => {
if (event.target){
const clickTarget = event.target;
clickTarget.classList.toggle('fav')
}
}
//Example use, get all favs and attach the text as a new element
const getFavs = () => {
const favs = document.querySelectorAll('.fav');
const favContainer = document.querySelector('.favs')
favContainer.innerHTML = "";
for( let fav of favs){
let newFav = document.createElement('div');
newFav.textContent = fav.textContent;
favContainer.appendChild(newFav)
}
}
.fav {
color: red;
}
<i class="" onclick="toggleFavourite(event)">1</i>
<i class="" onclick="toggleFavourite(event)">2</i>
<i class="" onclick="toggleFavourite(event)">3</i>
<i class="" onclick="toggleFavourite(event)">4</i>
<i class="" onclick="toggleFavourite(event)">5</i>
<button id="getFavs" onclick="getFavs()">Get Favs</button>
<section class='favs'>
</section>

How to implement a toggle button link?

<script>
function setSortMethod(param) {
var sortMethod = "#sortMethod";
var asecending = false;
var currUrl = "";
var currSort = "";
var outputUrl = "";
currSort = "sortMethod=" + param;
if ($('#filterPending')[0].checked == false {
outputUrl = (currSort);
}
window.location.href = "?" + outputUrl;
}
</script>
<button type="button" class="btn btn-link" id="action" onclick="setSortMethod('StartDate')" value="LeaveDate">
Leave Date
</button>
So I am trying to get this link button working to toggle between ascending and descending sorting order.
../Index?sortMethod=StartDate which sort the display data by
ascending order
../Index?sortMethod=StartDate_desc will sort the display data by
descending order
I have tried using a boolean variable toggle true/false but to no avail.
Backend c# code I already have the ViewBag with ternary
ViewBag.StartDate = sortMethod == "StartDate" ? "StartDate_desc" : "StartDate";
With switch case it will work if you manually key in the url.
But because right now I am reworking on the link button I changed from actionlink to bootstrap's button link, so I have to find some ways to get the "StartDate" parameter for this onclick="setSortMethod('StartDate') passed into setSortMethod function and try to toggle between StartDate or StartDate_desc.
Trying out razor syntax with ViewBag,
#{
string sortMethod = ViewBag.StartDate;
}
but I am not sure what can I do with this.
Try this One.
<button type="button" class="btn btn-link" id="action" onclick="setSortMethod('StartDate')" value="LeaveDate">
Leave Date
</button>
<script>
function setSortMethod(param) {
var sortMethod = "";
var asecending = false;
var currUrl = "";
var currSort = "";
var outputUrl = "";
currSort = "sortMethod=" + param;
window.location.href += "?" + currSort
}
</script>

Active nav bar doesn't change the first time

I am trying to change navigation a tag color when the user clicks on the <a> tag. The JS is working fine, except the first time the user clicks on the <a> tag; only in the second time the a tag color changes.
JavaScript:
function toggleNav(pageId){
activeColor();
var href = 'html/' + pageId + '.html';
window.onload = document.getElementById('main').innerHTML =
loadPage(href);
}
function activeColor(){
var header = document.getElementById("allNav");
var btns = header.getElementsByClassName("notActive");
for (var i = 0; i < btns.length; i++) {
var button1 = btns[i];
button1.addEventListener("click" ,
function() {
var current = document.getElementsByClassName(" active");
console.log(current.length);
for (var i = 0; i < current.length + 1; i++) {
current[0].className = current[0].className.replace("
active", "");
}
var myString = this.id;
var stringLength = myString.length;
var lastChar = myString.charAt(stringLength - 1);
if(lastChar == "2"){
var add = document.getElementById(this.id);
var id2Nmae = add.id.slice(0, -1);
var add2 = document.getElementById(id2Nmae);
add.className += " active";
add2.className += " active";
}
else{
var add = document.getElementById(this.id);
var id2Nmae = add.id + "2";
var add2 = document.getElementById(id2Nmae);
add.className += " active";
add2.className += " active";
}
});
}
}
HTML :
<div id="allNav">
<div class="sidebar" id="mySidebar" style="display:block">
<button id="open" onclick="Toggle()">
<a ><i class="fas fa-bars"></i></a>
</button>
<i class="glyphicon glyphicon-screenshot"></i>
<i class="glyphicon glyphicon-exclamation-sign"></i>
<i class="fas fa-burn"></i>
<i class="fas fa-utensils"></i>
<i class="fa fa-line-chart"></i>
<i class="far fa-comments"></i>
<i class="fas fa-bell"></i>
</div>
I succeeded to solve the problem, It was an issue I made by the DOM path not correct.
In the first time the page loads, the default load was the "goals" id by the next JS code:
var href = 'html/goals.html';
window.onload = document.getElementById('main').innerHTML = loadPage(href);
In this why the "addEventListener" needed to load at the first time and only in the second time the function can run.
I changed the default function to:
toggleNav('goals')
I hope I helped if somebody will experience the same issue.
Thanks for the help.
I ran your script and in the console I got
Uncaught TypeError: Cannot read property 'id' of null
(in chrome dev tools) Have you checked the element view (next to console) to see how the javascript is interacting with the HTML?
from looking at the code, the number "2" is for ids that are selected, however, everything ends with the number 2 and it is never actually removed. Is that intentional?
The loop doesn't seem to like "this.id" as it loses the reference (error above).
have you put in alerts to see where the pointer is in the loop?

HTML and JS : Capture Key Value pairs in HTML form

I have a Spring MVC application where I am required to capture a variable number of key value pairs based on user input. The HTML & JS part of the code to render the controls is as follows :
<tr>
<td><label>Attributes (Names & Value(s))</label></td>
<td><input id="Button1" type="button" value="Add" onclick="Button1_onclick()"/></td>
</tr>
<script language="javascript" type="text/javascript">
var NumOfRow = 1;
var attribs = {};
function Button1_onclick() {
NumOfRow++;
// get the reference of the main Div
var mainDiv = document.getElementById('MainDiv');
// create new div that will work as a container
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'innerDiv' + NumOfRow);
//create span to contain the text
var newSpan = document.createElement('span');
newSpan.innerHTML = "Attribute Type";
// create new textbox for type entry
var newTextBox = document.createElement('input');
newTextBox.type = 'text';
newTextBox.setAttribute('id', 'DimensionType' + NumOfRow);
//create span to contain the text
var newSpan2 = document.createElement('span');
newSpan2.innerHTML = "Attribute Value(s)";
// create new textbox for value entry
var newTextBox2 = document.createElement('input');
newTextBox2.type = 'text';
newTextBox2.setAttribute('id', 'DimensionValue' + NumOfRow);
// create remove button for each attribute
var newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = 'Remove';
newButton.id = 'btn' + NumOfRow;
// attach event for remove button click
newButton.onclick = function RemoveEntry() {
var mainDiv = document.getElementById('MainDiv');
mainDiv.removeChild(this.parentNode);
NumOfRow--;
}
// append the span, textbox and the button
newDiv.appendChild(newSpan);
newDiv.appendChild(newTextBox);
newDiv.appendChild(newSpan2);
newDiv.appendChild(newTextBox2);
newDiv.appendChild(newButton);
// finally append the new div to the main div
mainDiv.appendChild(newDiv);
}
}
</script>
I am not sure how to send this captured data back to my controller when the form is submitted. Please advise. Also if there is a better way to capture such data, those suggestions are most welcome as well.
What about making Capture key event in a text field you can do this :
<html>
<head>
<script language="JavaScript" type = "text/javascript">
<!--
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event)
{
if (document.all) //Checks for IE 4.0 or later
{
document.form1.text2.value = String.fromCharCode(event.keyCode);
}
else if (document.getElementById) //checks for Netscape 6 or later
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
else if (document.layers) //Checks for Netscape 4
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
}
//-->
</script>
<title>Capture Key Pressed</title>
</head>
<body>
<form name="form1">
<b>Type value in field: See what you typed:</b><br>
<input type = "text" name = "text1" onKeyPress="DisplayMsg(event)" size="20">
<input type = "text" name = "text2" onKeyPress="DisplayMsg(event)" size="20">
</form>
</body>
</html>

Categories

Resources