Show submit when checkbox is checked loop - javascript

I've got a page in wordpress that displays around 20 poll questions (using WP-polls).
I'm using a snippet to display the submit button for each poll once an answer has been checked. Thing is, with this snippet I have to copy paste it about 20 times, because of that I some kind of loop.
This is the current code I'm using
$(document).ready(function() {
var $submit = $("#btn-7").hide(),
$cbs = $('input[name="poll_7"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-6").hide(),
$cbs = $('input[name="poll_6"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-5").hide(),
$cbs = $('input[name="poll_5"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
As you can see what changes is the "btn_number" ID and "poll_number". This goes on for another 20 snippets. How can I make this dynamic?

jQuery allows you to use wildcards, for example:
var $submit = $("#btn-*").hide(),
$cbs = $('input[name="poll_*"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
Edit: I see the wildcard selectors isn't supported by jquery anymore (as above example) you might want to look at: http://james.padolsey.com/javascript/regex-selector-for-jquery/ which gives you the ability to use regex to define the selectors for all btn's and code for it once

You can use the starts with selector on the ID and name attributes, to dynamically access the number. The change event is more appropriate than the click event for checkboxes.
Demo
$('[id^="btn-"]').hide();
$('input[name^="poll_"]').change(function(){
var number = this.name.replace('poll_', '');
$('#btn-' + number).toggle( $(this).is(":checked") );
});
It would be better to use data-* attributes to link the buttons and checkboxes, or nest them in an element that has the ID. Parsing the number out of the ID attribute isn't the cleanest way.

You don't have to repeat the same code for 20 times just for getting different button ids. you can make it dynamic. checkout this simple example
$("#submit").click(
function()
{
for(i=1;i<=5;i++)
{
msg = $("#btn-"+i).val()
alert(msg)
}
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="button" id="btn-1" value="button1">
<input type="button" id="btn-2" value="button2">
<input type="button" id="btn-3" value="button3">
<input type="button" id="btn-4" value="button4">
<input type="button" id="btn-5" value="button5">
<p>
<input type="button" value="submit" id="submit">

$(document).ready(function(){
for(var i=1;i<=20;i++){
var submit = $("#btn-"+i).hide(),
cbs = $('input[name="poll_'+i+'"]').click(function(){
submit.toggle($this.is(":checked"));
});
}
});

Related

how to get value by data id in javascript?

Consider I have user data-rowid="123" and its value is data-loc="abc"
I want to get data-loc value find by data-rowid
here is my original html
<input type="checkbox" data-rowid="{{ $customer->id }}" data-loc="{{ $customer->location_url }}"/>
i have button when user click on it then it call that finction .map-checked-box
javascript which i tried
$("body").delegate('.map-checked-box', 'click', function(){
var a = $(this).data('id');
var b = $(this).find.('a').data("loc");
console.log(b);
});
**but this code only get data-rowid in (a) but doesnot find loc value
any help will be thankfull**
Like this :
$("input[type='checkbox'][data-rowid='"+ yourRowId +"']").attr("data-loc")
There are a bunch of inconsistencies in your code, along with a long-ago deprecated call to delegate - but the below should hopefully demonstrate how you can use filter to find an element by data-rowid and then read data-loc:
$("body").on('click', '.map-checked-box', function(){
var result = $('input').filter( (i,e) => $(e).data("rowid") == 123).data("loc");
console.log(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-rowid="123" data-loc="abc"/>
<button class="map-checked-box">click me</button>

How to increment the name attribute array using javascript function

I want to increment the value of the name attribute whenever the function is called. Below I have added all the code through which I add new text boxes using jQuery clone function. Hope now everything is clear.
function addQuestion(){
var question = jQuery('#question-template').clone();
question.css("display","block").removeAttr('id');
jQuery('#questions').append(question);
}
function renameQuestions(){
jQuery('.question-box').each(function(i,v){
jQuery(this).find('.question_id').html(i);
});
}
jQuery('#add-question').on('click', function(e) {
e.preventDefault();
addQuestion();
renameQuestions();
});
jQuery(document).on('click','.del-question', function(e)
{
e.preventDefault();
jQuery(this).closest('.question-box').remove();
renameQuestions();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="quiz[0][english][ques_title]" class="ques_title" placeholder="Enter question title" value="">
<textarea name="quiz[0][english][ques_desc]" class="ques_desc" rows="4" placeholder="Explaination here...."></textarea>
<a id="add-question" class="button" href="#">Add</a>
<a class="del-question button" href="#" data-id="1">Remove</a>
I want to increment the value quiz[0], whenever the add-question button is clicked, I tried using PHP adding a PHP variable in the JS function. But then I got to know it will not work because one is server side and other is client side scripting.
Demo: http://jsfiddle.net/GCu2D/5163/
JS:
function renameQuestion() {
var question = $(".question-box:last");
var total_question = parseInt((".question-box input:first").attr("name").replace( /^\D+/g, ''))+1;
question.find("input").each(function() {
var elem = $(this);
elem.attr("name", elem.attr("name").replace(/[0-9]/g, total_question));
});
}
This should solve your issue.

JQuery get formaction and formmethod

I have the a like this one
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button" onclick="popisgolubova_radiobutton(this)">
<input name="rodovnik" type="button" formaction="rodovnik.php" formmethod="post" formtarget="_blank" value="rodovnik" class="button" onclick="popisgolubova_radiobutton()">
<input name="podaci" type="button" value="poodaci" formaction="podaciogolubu.php" formmethod="post" formtarget="_blank" class="button" onclick="popisgolubova_radiobutton()">
</form>
and javascript
function popisgolubova_radiobutton(element)
{
alert($(element).find("[formaction]").val());
var popisgolubova_radiobutton=$("input[name=RadioGroup1]").is(":checked");
if(popisgolubova_radiobutton==false)
{
alert("nop");
}
else
{
$("form#popisgolubova_form").submit();
}
}
First I'm checking if any checkbox is checked or not and if it is the I can submit the form. But the problem is formaction, formmethod and formtarget. how to get them and submit them
To get the action or method attributes of a form you can try something like below:
$(function() {
var action = $("#formid").attr('action'),
method = $("#formid").attr('method');
});
Hope this helps to get an idea to solve ur problem
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button postForm"/>
</form>
$(document).on('click', '.postForm', function () {
$('#popisgolubova_form').attr('action', $(this).attr('formaction'));
$('#popisgolubova_form').attr('method', $(this).attr('formmethod'));
$('#popisgolubova_form').attr('formtarget', $(this).attr('formtarget'));
});
So the question is talking about the unfortunately named
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction
...which is a way to override
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-action
per clicking a properly set up submit button. The place you want to check this is upon submit - when you're sure things are actually being submitted.
The button you used to submit is stored as :focus - this does not seem to be otherwise stored in the event object at the moment.
$('form').on("submit", function(event) {
if( $(':focus').is('[formaction]') ) {
console.warn($(':focus').attr('formaction'));
}
if( $(':focus').is('[formtarget]') ) {
console.warn($(':focus').attr('formtarget'));
}
});
if( $(':focus').is('[formaction]') ) {
console.log($(':focus').attr('formaction'));
}
I had this problem and after searching the web I couldn't find a proper answer. Finally, I realized it's so simple.
When you add an event on form.submit you have an event argument that contains e.originalEvent.submitter, just use it as follows:
$('form').submit(function(e){
var url = form.attr('action');
if (e.originalEvent.submitter) {
var frmAction = $(e.originalEvent.submitter).attr('formaction');
if (frmAction)
url = frmAction;
}
,.....
});
You can use the samething for the formmethod as well.

Best way to pass JS/ css info to a form

I am sure this is so easy and I'm just a huge huge noob. I have a form on a PHP page, and it has a few normal form elements (1 textarea, 1 text field).
I am also dynamically adding 100 small images to the page, which are random, and I am using JQuery to let someone select or deselect these images:
Here is the html that loops 100 times to display the images:
<div class='avatar'><img class='avatar_image' src='$this_profile_image' name='$thisfriend'></div>
and here is the Jquery:
<script type="text/javascript">
$(document).ready(function() {
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
});
</script>
What I want to do is, when the form is submitted, have the script that processes it be able to tell which of those 100 images is selected (so it's class will be "red" instead of "avatar_image"). I am blanking on this.
You'll need to add hidden inputs with some kind of identifiers for those images, and toggle the state of those inputs based on the image selected-ness. Something like this:
Change your image markup:
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend'>
<input type="hidden" name="avatar_image[]" value="$this_profile_image" disabled="disabled" />
</div>
Change jQuery binding (and use event delegation, maybe pick a better container than document.body):
<script type="text/javascript">
$(function() {
var selClass = 'red';
$(document.body).on('click', ".avatar_image", function() {
var $this = $(this);
var $inp = $this.siblings('input[type="hidden"]');
var isSelected = $this.hasClass(selClass), willBeSelected = !isSelected;
$this.toggleClass(selClass);
if(willBeSelected) {
$inp.removeAttr('disabled');
} else {
$inp.attr('disabled', 'disabled');
}
});
});
</script>
Read the submitted data in PHP (assuming you're submitting via a POST form):
$selectedImages = $_POST['avatar_image'];
Add a ID to each image, when its clicked grab the id and then inject it into a hidden textfield
<input type="hidden" name="avatar" id="avatar" value="" />
$(".avatar_image").click(function() {
$(this).toggleClass("red");
//assign its id to the hidden field value
$("input[name='avatar']").attr('value', $(this).attr('id'));
// pass that to your DB
});
I presume your using ajax to grab this data back
success : function(callback){
$("image[id*='"+callback.avatar+"']").addClass('red');
}
Try this
PHP: Add the id for the friend to the html you had
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend' data-id='$thisFriendsId>
</div>
JS: Create an empty array. Use each function to go through push the selected id into your array. Then use post to submit to your php.
selected = [];
$(function(){
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
$('.submit').click(function(){
$('.red').each(function(){
var selectedId = $(this).data('id');
selected.push(selectedId);
});
$.post ('http://mysite.com/process.php', selected, function() { alert('succes!'); });
});
​});​

Jquery get each div's sub child divs and grab info into an array

I have a some html that looks like this
<div id="main">
<div id="sub_main_1" class="sub_main">
<input type="text" class="sub_name_first" /><br />
<input type="text" class="sub_name_second" /><br />
</div>
<div id="sub_main_2" class="sub_main">
<input type="text" class="sub_name_first" /><br />
<input type="text" class="sub_name_second" /><br />
</div>
</div>
I would like to pull out each sub_main divs information into an array in javascript. So far I have this as my jquery code
$('#main').find('.sub_main').each(
function() {
alert('hi');
});
The alert is just a test that it should show "hi" twice. But this is not working. I am also not clear on how I can store the two inputs in a javascript array. Any help would be great! Thanks,
var array = $('#main input').map(function() {
return $(this).val();
}).get();
EDIT:
Note that this will return the values of all input elements under #main. You can make the $('#main input') selector as specific as you need if not all input elements are desired.
var info = $("#main .sub_main input:text").map(function() {
return $(this).val();
}).get(); // get() converts resulting collection into array
http://api.jquery.com/map/
Are you waiting for the DOM to load?
$(document).ready(function(){
$('#main').find('.sub_main').each(
function() {
alert('hi');
});
});
if you want to pull out the child divs of your 'main' div, use
$('.main>div')
This will select all div children of anything with the class of 'main'.
why not just do something simple like this:
var firsts = [];
var seconds = [];
("#main .sub_main input").each(function(){
var $this = $(this);
if($this.is(".sub_name_first"){
firsts.push($this.val());
} else {
seconds.push($this.val());
}
});
sure, its not the best way, but i just wrote that in 1 minute and it works

Categories

Resources