How to increment the name attribute array using javascript function - javascript

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.

Related

Color input's border when nothing is entered doesn't work

I have an input text that has to be something in it for the form to work.
So I wish to add some functionality to the Confirm button that checks if the input field is empty, and if so, recolor the border of that input.
I'm doing the following:
$(function mainListeners () {
"use strict";
var confirm = $('#addNewConfirm');
var cancel = $('#addNewCancel');
var eventBox = $('#eventname_input');
console.log("RUNS!!");
confirm.onclick = function (e) {
if (eventBox.val() == ''){
//so if we have an empty event
//recolor borders.
console.log("CHANGES!!");
eventBox.css('border-color','#d81919');
}else {
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="yesno IFlexible">
<button id="addNewConfirm" >Confirm</button>
<button id="addNewCancel">Cancel</button>
</div>
<div >
<label>Event:</label>
<input id="eventname_input" type="text" />
</div>
Here I get no errors and I always see the RUNS!! message, so my script is attached. However, I never see the CHANGES!! message, so the condition eventBox.val() == '' is never true. I looked up the internet on how to check if an input text's text is empty, and this is what I found, and it clearly isn't working.
How can I sort out this recolor of border if the input has no text?
Use JQuery click() function instead of onclick like so:
$(document).ready(function() {
var confirm = $("#addNewConfirm");
var cancel = $("#addNewCancel");
var eventBox = $("#eventname_input");
console.log("RUNS!!");
confirm.click(function(e) {
if (!eventBox.val()) {
console.log("CHANGES!!");
eventBox.css("border-color", "#d81919");
} else {
eventBox.css("border-color", 'inherit');
// whatever you want
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="yesno IFlexible">
<button id="addNewConfirm">Confirm</button>
<button id="addNewCancel">Cancel</button>
</div>
<div>
<label>Event:</label>
<input id="eventname_input" type="text" />
</div>
Try using either the Jquery method of setting a click event (.click()) or the vanilla JS way of retrieving a DOM element(document.getElementById()).
Below is a working example of changes!! getting called.
$(function mainListeners () {
"use strict";
var confirm = document.getElementById('addNewConfirm'); //GET DOM ELEMENTS THIS WAY OR SEE BELOW FOR CLICK
var cancel = $('#addNewCancel');
var eventBox = $('#eventname_input');
console.log("RUNS!!");
confirm.onclick = function (e) {//OR CHANGE THIS TO CLICK()
if (eventBox.val() == ''){
//so if we have an empty event
//recolor borders.
console.log("CHANGES!!");
event.css('border-color','#d81919');
}else {
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="yesno IFlexible">
<button id="addNewConfirm" >Confirm</button>
<button id="addNewCancel">Cancel</button>
</div>
<div >
<label>Event:</label>
<input id="eventname_input" type="text" />
</div>
The fact is that onclick is vanilla Javascript and you are trying to use it on the confirm jQuery object.
In order to fix it, you can use confirm[0].click = function(e) syntax or confirm.click(function (e). I suggest you to use jQuery syntax: if you load this library you are encouraged to use it in order to strengthen readability.

Function to get input and assigns it to variable

I'm trying to make something using javascript/jquery that is similar to java.
The way to get input in java:
String x = JOptionPane.showInputDialog("Enter a value: ");
.showInputDialog shows GUI and submits a value after "Submit" is clicked.
This is what I've tried: https://jsfiddle.net/1t5pxhj5/2/
This behavior is not possible with Javascript.
You should use events and callbacks to retrieve the specified value.
Your Java code:
String x = JOptionPane.showInputDialog("Enter a value :");
Your Javascript code:
function showInput(message, callback) {
// display dialog
// ...
callback($("input").val()); // this should be returned to getInput after Submit is clicked
});
showInput("Enter a value:", function(x) {
// do something now
});
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="gettext('txt');"/>
to retrieve data use code below
function gettext(id) {
var entereddata = document.getElementById(id);
var value = entereddata.value;
}
Hope my code works. Keep coding
Supposing you have
<input type="text" class="my-input">
<button>click me!</button>
you can retrieve input value in jQuery/Javascript with this instruction;
$(".my-input").val();
if you want to bind the data retrieval to the "click me!" button there is the complete code:
$(".click-me").click(function() {
alert($(".my-input").val());
});

jQuery/Javascript - Get value of text input field, and display in div

I am testing getting a text input, and printing the result in a div below. However, I can't see to get it to work.
If the "placeholder" of the input field to a "value", it inexplicably works. I may just be tired, and missing something obvious, but I can't for the life of me work out what's wrong.
//Tested and didn't work
//var URL = document.getElementById("download")[0].value;
//var URL = document.getElementsByName("download")[0].value;
var URL = $('#download').val();
function downloadURL() {
//Print to div
document.getElementById("output").innerHTML = URL;
//Test, just in case innerHTML wasn't working
alert(URL);
}
<p><input type="text" name="download" id="download" placeholder="Download URL"></p>
<button onclick="downloadURL()">Test</button>
<div id="output"></div>
Just a small change, you have to get value when you click on button, so first save a reference to that field and then get value when required
var URL = $('#download');
function downloadURL(){
//Print to div
document.getElementById("output").innerHTML = URL.val();
// alert(URL.val());
}
If you want to go jQuery...
var URL = $('#download');
function downloadURL() {
$("#output").html(URL.val());
}
... or plain JavaScript
var URL = document.getElementById("download") ;
function downloadURL() {
document.getElementById("output").innerHTML = URL.value;
}
I'd recommend you to stick with jQuery. Let jQuery behave in an unobtrusive way instead of relying on an inline event handler attached to the button.
<p> <input type="text" name="download" id="download" placeholder="Download URL"></p>
<button>Test</button> //remove the inline click handler
<div id="output"></div>
$('button').on('click', function() {
var url = $('#download').val();
$('#output').text(url); //or append(), or html(). See the documentation for further information
});
Minor modifications on your code so that it can be aligned to "Unobtrusive Javascript".
HTML
<p>
<input type="text" name="download" id="download" placeholder="Download URL">
</p>
<button id="btnDownloadUrl">Test</button>
<div id="output"></div>
jQuery
$(function(){
$("#btnDownloadUrl").bind("click", function(){
var downloadUrl = $("#download").val();
$("#output").html(downloadUrl);
});
});

Show submit when checkbox is checked loop

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

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!'); });
});
​});​

Categories

Resources