Javascript change button text by value - javascript

Maybe I'm not googling right but I have a simple question that I was not able to find an answer. I have a group of buttons with specific text. Because the page is dynamic depending on the user choices there may be five buttons cut for example.
<button>Cut</button>
<button>Copy</button>
<button>Speak</button>
<button>Fullscreen</button>
Above you can see one group but there might be the same buttons copied 10 times. I want to change the text of those buttons by getting their value. For example:
Getting all buttons with text "Cut" and change their value to "foo"
Then I want to do something similar with other text to the other buttons. How to do that?

Use document.querySelectorAll to select all the buttons and iterate through them using forEach loop. Check their text using textContent and if it is Cut set it to foo
document.querySelectorAll('button').forEach((e)=>e.textContent=='Cut'?e.textContent="foo":false)
<button>Cut</button>
<button>Copy</button>
<button>Cut</button>
<button>Speak</button>
<button>Cut</button>
<button>Fullscreen</button>
<button>Cut</button>

I would suggest getting all the buttons using document.getElementsByTagName() and filtering based on the content. Then you can iterate over your filtered array and perform whatever modifications you want:
// get all buttons as an array
const buttons = Array.from(document.getElementsByTagName("button"));
// filter the array using a strict string equality check
const cutButtons = buttons.filter(button => button.textContent === "Cut");
// perform your modifications
cutButtons.forEach(button => {
button.textContent = "foo";
});

You can use querySelectorAll() to get all the buttons. Then loop through them to check the textContent to modify the button:
var btn = [].slice.call(document.querySelectorAll('button'));
btn.forEach(function(b){
if(b.textContent == 'Cut')
b.textContent = 'foo';
});
<button>Cut</button>
<button>Copy</button>
<button>Speak</button>
<button>Fullscreen</button>
<button>Cut</button>

Get buttons by tag name using getElementsByTagName() then with in for loop check content and change it if "Cut" using Node.textContent
var cut=document.getElementsByTagName("button");
for(var i=0;i<cut.length;i++){
if(cut[i].textContent=="cut"){
cut[i].textContent="foo"
}
}

Related

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

Catch all radiobuttons inside a div using jQuery

Someone knows how can I get all the radiobuttons inside a div? The div has a id as follows
<div id="quest{{ $groups }}" class="quest">
I'm using Laravel, therefore my idea is to get the values inside a div, and put in jQuery something like
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
But this doesn´t work, so I want to know how to get all the radiobuttons inside a div an do a loop inside using .each I think.
I need to duplicate one group of questions and then be able to do a validation, but only works for the first group, the second group is not validated and I´ve checked the id value for each radiobutton and change to previousid_2, and the questionnaire is cloned. Also I want to know how can I reset the values when I clone the questionnaire, because if you have select YES NO YES NO, in the second group when you clone it, those results are selected and the disabled fields too.
You're actually asking for several things. Your code implies you have access to the current group in a variable called groups. so...
1) select all radio inputs within a div:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2) Loop over them, and do some work on each element:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3) Duplicate a group of radio buttons:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4) Run validation on a specific group
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
You can get all radio buttons and iterate on them like following
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
it's very simple using Id's
To get all the elements starting with "quest" you should use:
$("[id^=quest]")
To get those that end with "jander"
$("[id$=quest]")
and the complete answer is
var radios = $("input[type='radio'][id^='quest']");
the point is what if you want to wildcard class :( :(
$("[class^=quest]")
on a dom like
<pre>
<a class="btn quest primary">link</a>
<pre>
it won't work , thus you will need a more complex wildcard that you have to till me when you find it :D
the fact is you will not need it , whenever you need to get a list of element using classes just use a common class :D
hope i helped u well

Javascript interchange with command button

I am trying to setup an interchange using two texts boxes with a command button in between.
The idea is you type a reference/code in the left hand text box, click the button and it generates an alternative reference/code in the right hand text box.
The point being the user can check alternate bearing references if they can't find what they are looking for with the one they have.
The code I use so far is:
<script type="text/javascript">
oldRef = new Array ("Z582","T608","A173");
newRef = new Array ("C850","S708","X449");
function convert()
{
document.getElementById("v2").value = "";
for (index=0 ; index < oldRef.length ; index++)
{
if ( document.getElementById("v1").value == oldRef[index] )
document.getElementById("v2").value = newRef[index];
}
}
</script>
V1 and V2 refer the the text box ID.
This works with the text boxes but I don't know how to incorporate the command button into this so that they need to click the button in the middle for it to generate.
Any suggestions would be much appreciated.
Best
Will
Its pretty Easy stuff what you need to do is to use onclick of the button like this
document.getElementById('button').onclick = function () {
document.getElementById("v2").value = "";
for (var index=0 ; index < oldRef.length ; index++) {
if (document.getElementById("v1").value == oldRef[index])
document.getElementById("v2").value = newRef[index];
}
}
Here is a demo
I hope this is waht you want....
So essentially there are two things that you need to accomplish what you asked. You need to create a element within your HTML, in this case a button. You then need to catch the event that you want to catch from that element and then execute you convert function.
This is one example of accomplishing this:
So create an button within your HTML
<button id="btn_command">Command</button>
Then in Javascript you want to target that button and add an event listener to that button. In the example the below the variable var btnCommand is set to the html button by using the getElementById method to get that button with that id. Then we add and event listener to that element that when clicked it executes your convert function.
var btnCommand = document.getElementById ("btn_command") ;
btnCommand.addEventListener("click", convert, false) ;
If you want to use jQuery you would do something like this.
$('#btn_command').on('click', function() { convert(); });
Here is another quick and dirty way to just test you button with your function. It is not a best idea to mix your javascript inline with your html but just to test your button and if your convert function is doing that you think you could just say
<button onClick="convert()">Command</button>
Well there are few ways to accomplish what you asked. Happy Coding!

Select an option of select box using the value

I have a dropdown box and I want to select the option based on value. Somehow I am getting handle to value say 3. Now I want to manually select the option which has got value 3.
I have tried something like this
selectBoxElement.options[selectedValues].selected = true;
where selectedValue = 3, but it is not working.
If using jquery (as per your tag), you can do:
$(document).ready(function() {
$("#yourSelectId option[value='3']").attr("selected", "selected");
});
Something like that should work (assuming $ is not overwritten and is alias for jQuery):
$(selectBoxElement).find('option[value="selectedValue"]').prop('selected', true);
or rather:
$(selectBoxElement).val(selectedValue);
which is simpler and achieves similar result :)
If you're using plain JS (except for the jQuery tag, you didn't explicitly say whether you want plain JS or jQuery), this should do what you want:
for (i=0; i<selectBoxElement.options.length; i++) {
if (selectBoxElement.options[i].value == selectedValues) {
selectBoxElement.options[i].selected=true;
break;
}
}
This is simple please try the following
When using the index position of the option tag within the select box
selectBoxElement.selectedIndex = index; // Where the index starts from 0
When using the value
selectBoxElement.value = value;// Where the value is the attribute defined within option tag
Hope this solves your problem.

selected link changes background

I have 2 menus, category and countries. I've made so far to change and keep background of one element but I have problem with simultaneous memory of other menu's element.
var lookaround=[];
function seleItem(obj,color){
if(lookaround[obj.className])
lookaround[obj.className].style.background=null;
lookaround[obj.className]=obj;
obj.style.background=color;
}
Example page is HERE
You should use an object instead of an array for lookaround:
var lookaround = {};

Categories

Resources