Catch all radiobuttons inside a div using jQuery - javascript

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

Related

Javascript change button text by value

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"
}
}

dynamically changing a div ID and other element's ID within the div

this is the div im trying to copy
{%for i in current_user.posts%}
<div class = "own_posts" id = "{{'id_' + i.id|string}}">
<img src = "{{url_for('static',filename='user_prof_pic/' + current_user.prof_pic)}}">
{{current_user.first_name}}
<p>{{i.post}}</p>
<div class ="like_comment">
<ul>
<li>like</li>
<li>comment</li>
</ul>
</div>
<form class ="comment_form">
<input type="text" action = "#" name = "comment_box" class ="comment_box" id = "{{'id_' +i.id|string}}">
<input type="submit" value="comment" class ="submit" id = "{{'id_' + i.id|string}}">
</form>
</div>
{%endfor%}
so far I've been successful at prepending it and changing the newly prepended div's ID using jquery like this.
var count = 4
$(".submit").click(function(event){
event.preventDefault()
var id = $(this).attr("id")
var comment = $(".comment_box#" + id).val()
console.log(count)
count++
$.ajax({
type:"POST",
url:"#",//"{{url_for('main.ProfilePage',user = current_user.first_name)}}",
data: JSON.stringify({"comments":comment}),
contentType:"application/json;charset=UTF-8"
});
var div_copy = $(".own_posts#id_2").clone()
var div_copy2 = div_copy.attr("id","id_" + count)
$("#own_stream").prepend(div_copy2)
});
however the form ID within the prepended div still contains the ID of the div it was cloned from. to clarify
var div_copy = $(".own_posts#id_2").clone() the form in this div contains an id of id_2 so the newly prepended div's form id is still id_2
I changed the prepended div's ID doing this:
var div_copy = $(".own_posts#id_2").clone()
var div_copy2 = div_copy.attr("id","id_" + count)
$("#own_stream").prepend(div_copy2)
but I don't know how to access the form within this newly cloned div and change it's form ID.
how do we achieve this?
also am I doing this right? Im trying to learn web development and wan't to understand how sites like facebook,twitter etc. are showing your newly posted statuses/tweets into the page without refreshing it.
is what I'm doing the gist of how that works? if not
shed some light on a newbie
also this is just a test to practice the concepts
If all you are attempting to do is retrieve the form element using jQuery, based on your source, you have multiple options.
var form = $(".own_posts#id_2 > form");
/* or */
var form = $(".own_posts#id_2 > .comment_form");
I don't normally suggest the direct descendant method because if your genealogy changes in the future, it will fail. You are using templates so intuitively I see future changes to it a possibility. Using a unique identifier or known singular class and searching the entire div chain makes more sense to me.
var form = $(".own_posts#id_2 .comment_form");
/* or */
var form = $(".own_posts#id_2").find(".comment_form");
Those two options should be roughly equivalent for your purpose and can use either.
Also I would be careful with non-unique ids. You may get away with it by only searching smaller scoping chains, but you're only supposed to have one on the page. This is why most functions that retrieve by id will return only the first object found, rather than a collection.
I don't know how you're using the ids, but perhaps something like id="{{'posts_' + i.id|string}}" and so on to utilize unique prefixes.

Access from change event to other input html jquery autocreate

My problem is:
I have a page with a table is auto generated with ajax-jquery
My table is 3 <td> 1: name 2-3: checkbox for parameters
I set event on all input:checkbox ("change") event.
The problem appears when i try to get check state of checkbox different than i click.
code:
$(document).ready(function() {
$("#permessiAttributiDiv").on("change", "input:checkbox", function() {
var IDPermesso = $(this).attr("id").substring(1);
var selezionatoSpuntato = (this.checked);
var altro = $(this).parent().find("input:checkbox").checked;
var scheda = $("#selectTipo").val();
});
)};
I also try to get check state by id but i always doesn't work......
I see if the checkbox is write in html static code all works ok but if i generate it with jquery i can't access to input with any selector.....
Can anyone help me?
Thanks
You must be getting error in console. See How to open the JavaScript console in different browsers?
The problem line which I see is
var altro = $(this).parent().find("input:checkbox").checked;
As $(this).parent().find("input:checkbox") will return you jQuery object and they don't have checked property.
You can use .not(this) to exclude the current element from the collection.
var altro = $(this).parent().find("input:checkbox").not(this).prop('checked');
OR
var altro = $(this).parent().find("input:checkbox").not(this).is(':checked');

How can I invisiblize groups of controls via jQuery?

In my Sharepoint project/Web Part/Web Page, I dynamically create page elements/controls using C# in the *.ascx.cs file.
In the *.ascx file, I use jQuery for responding to events that happen on the page (selections, changes of checkbox states, etc.).
I have a need to conditionally invisiblize groups of controls/elements on the page. Specifically, if the user checks a certain checkbox, I can "remove" whole swaths of the page that, in that scenario, don't apply to her.
How can I do this? I've got this starting point:
/* If the select "Yes" (they are seeking payment for themselves, as opposed to someone else), omit (invisibilize) sections 2 and 3 on the form */
$(document).on("change", '[id$=ckbxPaymentForSelf]', function () {
var ckd = this.checked;
if (ckd) {
// what now?
}
});
I could do it the hair-pulling-out way (which would be very painful for me, because I have almost as much hair as Absalom did), and set each individual element, like so:
if (ckd) {
var $this = $('[id$=txtbxthis]');
var $that = $('[id$=txtbxthat]');
var $theother = $('[id$=txtbxtheother]');
. . . // store a reference to all the other to-be-affected elements in vars
$this.visible = false; // <= this is pseudoscript; I don't know what the jQuery to invisiblize an element is
$that.visible = false; // " "
$theother.visible = false; // " "
. . . // invisiblize all the other to-be-affected elements
}
Surely there's a more elegant/better way!
Is it a matter of assigning all the conditionally invisible elements a particular class, and then invisiblizing every element that is assigned that class, or what?
Also, I want the area formerly used by this now-invisible swath to "go away" or "roll up" not sit there with a blank stare, yawning chasm, or Gobi Desert-like featureless expanse.
there are a number of ways to do this. but in your jquery implementation I would decorate the elements with data tags that will tell the code which elements to hide and show.
<input data-group="1" type="text" />
<input data-group="2" type="text" />
var $group1 = $('*[data-group="1"]');
var $group2 = $('*[data-group="2"]');
if (ckd) {
$group1.hide();
$group2.show();
}
else{
$group2.hide();
$group1.show();
}
You could do the same thing with css classes as well but I prefer using the data attribute
If you can group your controls using classes, you could select the class which needs to be hidden in that particular scenario and just use the hide() function:
if (ckd) {
var cls = getClassForCurrentScenario();
$("." + cls).hide(); //slideUp() would be an animated alternative
}
If the controls can be grouped inside a div, for example, then you'd just need to hide that element:
if (ckd) {
var id = getElementIdForCurrentScenario();
$("#" + id).hide(); //slideUp() would be an animated alternative
}
It really depends on how you manage to group your controls into "target groups", so that you can efficiently access them later.
You can hide an element like so:
$('...').hide();
Or you can slide it up with:
$('...').slideUp();
to get a nice sliding up animation.
On a side note, you can do this to multiple elements at once, in your case:
$('[id$=txtbxthis], [id$=txtbxthat], [id$=txtbxtheother]').slideUp();

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!

Categories

Resources