jQuery get only first id value from the loop - javascript

My code is:
<input id='edit' type='checkbox' />
while($rs = mysql_fetch_array($query_fetch))
{
echo "
<input type='text' name='qty' id='qty' value='".$sum[0]."' disabled>
";
}
<script>
document.getElementById('edit').onchange = function() {
document.getElementById('qty').disabled = !this.checked;
};
</script>
The problem is that when check the checkbox only the first row of the loop is effected. I want when checkbox is checked all input to be enabled.

To do this in jQuery, change:
<input type='text' name='qty' id='qty' value='".$sum[0]."' disabled>
To:
<input type='text' name='qty' class='qty' value='".$sum[0]."' disabled>
And add the following code:
$('#edit').click(function() {
if ($(this).prop('checked')) {
$('.qty').prop('disabled', false);
} else {
$('.qty').prop('disabled', true);
}
});
Note: DOM object IDs should be unique. No two elements should have the same ID. You can assign the same class to multiple elements and identify them in javascript that way. Also, if these input elements are form elements you plan to process server side, you will need to name them differently or only the last value assigned will be available.

First thing You don't use id for that much elements... id is unique for each element...
here you can use class = qty .
you can get class values using jquery
$('.qty').eq(0).val();
still if you want to use id then you can concatenate any counter variable (i) to id
echo "
<input type='text' name='qty"+i+"' id='qty' value='".$sum[0]."' disabled>
";

To do this in jQuery:
add class entry to the text fields:
<input type='text' class='qty' name='qty' id='qty' value='".$sum[0]."' disabled>
and then use the jquery
$( "#edit" ).click(function() {
$( ".qty" ).each(function( index ) {
if ($("#edit").is(':checked')) {
$( this ).prop('disabled', false);
} else {
$( this ).prop('disabled', true);
}
});
});

Related

Dynamically generated html using Javascript object does not pick up Bootstrap or CSS styling

I wish to generate and insert some new html into my webpage on clicking a button as such.
document.getElementById("generate").addEventListener("click", function(event){
// Get number of steps user has typed in
steps = document.getElementById("steps").value;
console.log(steps);
if (steps == ""){
alert("Please provide number of synthetic steps");
}
// Once click generate button, delete it and steps field to prevent being clicked again.
if (steps != ""){
// Array of elements wish to remove
var removal = ["#steps", "#generate", "#field-wrap"];
for (var i in removal){
$(removal[i]).remove();
}
var page = new pages(steps);
// Obtain html to show in first wrapper
var initial_html = page.initial();
// Put initial html after first box id
$('#wrapper').append(initial_html);
}
});
The page is styled using Bootstrap and I know the static content all works fine with this. The new html content is generated from the Javascript object, "pages":
function pages(step){
this.step = step;
// Function to insert in JME window. Note, had to change id to
jsme_container1 in html and script to enable function to place canvas in correct position.
this.draw = function jsmeOnLoad () {
document.JME2 = new JSApplet.JSME("jsme_container1", "300px", "250px");
// Add identifier to JME object
document.JME2["step"] = this.step;
// Push on to global array
drawing_objects.push(document.JME2);
}
// html to display in place of generate button for first JME object
this.initial = function(){
return "<div id=‘field-wrap’><div id=‘button’><div class='form-groups' style='padding-bottom:5px;'><input autocomplete='off' autofocus class='form-control' name='Quantity'placeholder='Quantity required' type='text' id='quantity' style='width:150px;'/></div><div class=‘dropdown’ style='position:absolute; top:0px; right:0px;'><button class=‘btn btn-primary dropdown-toggle’ id=‘touch’ type=‘button’ data-toggle=‘dropdown’>grams <span class=‘caret’></span></button><ul class=‘dropdown-menu’ id=‘menu’><li><a href=‘#’>milligrams</a></li> <li><a href=‘#’>grams</a></li><li><a href=‘#’>kilograms</a></li></ul></div></div> <form role=‘form’> <div class=‘form-group’><input type='text' class=‘form-control input-sm’ id=‘moles_start’ autocomplete='off' class='0' autofocus class='form-control' name='moles' placeholder='Moles' readonly/></div> <div class=‘form-group’> <input type='text' class=‘form-control input-sm’ autocomplete='off' class='0' autofocus class='form-control' name='smiles' placeholder='Smiles' readonly/> </div> <div class=‘form-group’><input type='text' class=‘form-control input-sm’ autocomplete='off' class='0' autofocus class='form-control' name='MW' placeholder='Molecular Weight' readonly/></div></form></div>";
};
}
I find that the html is inserted into the document fine using the jQuery method "append()", however it is not styled at all like the rest of the document ie it does not seem to pick up and of the Bootstrap and/or document's own CSS. I was wondering if I could get some pointers as to why this might be? Thanks
Yep the issue is in quotes indeed. Look at how those class names and id's look in dev tools.
All you need is to find and replace those ‘bad’ quotes.
There's something wrong with the quotation marks of your returned html. You used ‘ and ’ instead of ' a couple of times. Try this:
this.initial = function(){
return "<div id='field-wrap'><div id='button'><div class='form-groups' style='padding-bottom:5px;'><input autocomplete='off' autofocus class='form-control' name='Quantity' placeholder='Quantity required' type='text' id='quantity' style='width:150px;'/></div><div class='dropdown' style='position:absolute; top:0px; right:0px;'><button class='btn btn-primary dropdown-toggle' id='touch' type='button' data-toggle='dropdown'>grams <span class='caret'></span></button><ul class='dropdown-menu' id='menu'><li><a href='#'>milligrams</a></li> <li><a href='#'>grams</a></li><li><a href='#'>kilograms</a></li></ul></div></div> <form role='form'> <div class='form-group'><input type='text' class='form-control input-sm' id='moles_start' autocomplete='off' class='0' autofocus class='form-control' name='moles' placeholder='Moles' readonly/></div> <div class='form-group'> <input type='text' class='form-control input-sm' autocomplete='off' class='0' autofocus class='form-control' name='smiles' placeholder='Smiles' readonly/> </div> <div class='form-group'><input type='text' class='form-control input-sm' autocomplete='off' class='0' autofocus class='form-control' name='MW' placeholder='Molecular Weight' readonly/></div></form></div>";
};

function for keypress event not triggered when typing too fast

FIDDLE DEMO
var oldValue;
$(document).on('keydown','.main', function (e) {
oldValue = $(this).val();
});
var newValue;
$(document).on('keyup', '.main',function (e) {
newValue = $(this).val();
foo(oldValue,newValue);
});
function foo(orig){
$('#table2').find('tbody tr').each(function (i) {
var $td2 = $(this).find('td input:text');
if (orig == $td2.val()) {
$td2.val(newValue);
}
});
}
This is what happens,if I change "Apple" on table 1 slowly typing, "Apple" input field changes, but If I type too fast, my code is not working.
What if you add some relation between the original input-field and the corresponding like:
<input type='text' class= 'main' value="Apple" rel="sec_apple"/>
and
<input type='text' value="Apple" class="sec_apple"/>
for the second input.
Then you javascript could look like this:
$(document).on('keyup', '.main',function (e) {
foo($(this));
});
function foo(orig){
rel = orig.attr('rel');
var sec = $('.' + rel);
sec.val(orig.val());
}
Demo
Use JavaScript rather than jQuery. jQuery has a lot of overhead and can be too slow.
Probably not the case here. You do need to explain the issue a little better.
I ran a test and could not miss a key stroke, with my code.
My test routine changes the color of the background on each onkeyup.
I only used the two text inputs in table 1 to the right of Apple and banana.
Because I do not understand what you are doing, my test routine changes the color of the background on each onkeyup. If I type in 123456789 as fast as possible in both text fields they both come end with the correct color.
You may notice that I declare the inputs globally and use arrays instead of if else. Things that cannot be done efficiently with jQuery.
The reason I abandoned jQuery is I found jQuery to be way too slow on an iPad.
The following is tested at: This test Location
<!DOCTYPE HTML>
<html lang="en"><head><title>keys</title></head><body>
Table1
<form id='form1'>
<table id='table1'><tbody>
<tr><td><input type='text' class= 'main' value="Apple"/></td>
<td><input id="t1" type='text' class= 'main' value="" onkeyup="key(1)"/></td>
</tr><tr>
<td><input type='text' class= 'main' value="Banana" /></td><td><input id="t2" type='text' value="" onkeyup="key(2)"/></td>
</tr></tbody></table>
Table2
<table id='table2'><tbody>
<tr><td><input type='text' value="Apple" /></td></tr>
<tr><td><input type='text' value="Banana" /></td></tr>
<tr><td><input type='text' value="Banana" /></td></tr>
</tbody></table>
<br />
</form>
<script type="text/javascript">
//<![CDATA[
var color = new Array;
color[0] = '#f00';
color[1] = '#f0f';
color[2] = '#ff0';
color[3] = '#0ff';
var nc=[0,0,0];
var next = [1,2,3,0];
var txt=new Array;
txt[1] = document.getElementById('t1');
txt[2] = document.getElementById('t2');
function key(id){
nc[id] = next[nc[id]];
txt[id].style.background=color[nc[id]];
}
//]]></script></body></html>

Jquery validate and submit more forms on one page

So I am dealing with some survey pages. First my makesurvey.php reads all questions and then create page for editing questions and creating new questions. Each question is in own form and it has own submit. Then admin of survey can on page makessurvey.php fix the existing questions and also can add new question which is subbmited to handlesurvey.php wich makes updates to database. That means on one page I have let's say 20 forms with submit button. Now I realise that I have encountered more problems. The survey will be handle only by one admin. And this survey apllication needs to work dynamic, because admin can enter some new question, later can delete some questions. After some time add new questions, then delete and so on.
PROBLEMS:
1.Problem: On page makesurvey when admin wants to edit survey how to make just one jQuery function, which will first validate then submmit form to handlesurvey.php. (admin will edit one question at time and press submit). The other option is to generate so many js functions for each form but I think that isn't appropriaty way, but I think it would work fine.
2.Problem: When admin adds/edits some question how should my handlesurvey.php know which variable is in $_POST[<some_variable>].
Generated makesurvey.php page:
<script type="text/javascript">
$("form#updateQuestion").submit(function(){
var SloQuestion = $("#SloQuestion").val();
var typeQuestion=$('#typeQuestion').val();
var RadioValue1=$('#RadioValue1').val();
var RadioValue2=$('#RadioValue2').val();
var RadioValue3=$('#RadioValue3').val();
var RadioValue4=$('#RadioValue4').val();
//HERE I WILL DO SOME VALIDATION
/* $.post( "editSurveyHandle.php", $("form#updateQuestion").serialize())
.done(function( data ) {
alert("You have changed question!");
/* });
return false;*/
});
</script>
</head>
<html>
<body>
<form id='updateQuestion1' name='updateQuestion1' method='post' action=''>
<input type='hidden' name='hidden' value='question1'/><table width='600px'><tr></tr>
<tr><td width='50%' valign='top'><label for='question1'><h2>CURRENT QUESTION: </h2></label></td></tr>
<tr><td>SLOVENIAN </td><td width='50%' valign='top'> <label for='question1'>Some question 1 *</label></td></tr>
<tr><td width='50%' valign='top'>TYPE QUESTION</td><td width='50%' valign='top'>RADIO BUTTON</td></tr>
<tr><td><h4>DELETE QUESTION</h4></td><td><input type='checkbox' id='deleteQuestion' name='deleteQuestion' value='delete'/></td></tr>
<tr><td><h4>CHANGE QUESTIOn</h4></td></tr>
<tr><td><label>SLOVENIAN</label></td><td><input type='text' id='SloQuestion' name='SloQuestion' size='50' value ='Velikost sobe *'></td></tr>
<tr><td>TYPE QUESTION </td><td><select id='typeQuestion' name='typeQuestion'>
<option value='text'>Malo vnosno polje</option>
<option value='textarea'>Textarea</option>
<option selected='selected' value='radio'>Izbirino polje</option>
</select></tr>
<tr><td></td><td><input type='text' id='RadioValue0' name='RadioValue10' size='50' value ='Bad'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue1' name='RadioValue11' size='50' value ='Sufficiently'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue2' name='RadioValue12' size='50' value ='Dobro'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue3' name='RadioValue13' size='50' value ='Excelent'></td></tr>
<tr><td></td><td><input type ='submit' id='submit' name='submit' value='Izvedi spremembe'/></td></tr>
</table>
</form>
<form id='updateQuestion2' name='updateQuestion2' method='post' action=''>
<input type='hidden' name='hidden' value='question2'/><table width='600px'><tr></tr>
<tr><td width='50%' valign='top'><label for='question2'><h2>CURRENT QUESTION:</h2></label></td></tr>
<tr><td>SLOVENIAN </td><td width='50%' valign='top'> <label for='question2'>Some question 2</label></td></tr>
<tr><td width='50%' valign='top'>TYPE QUESTION</td><td width='50%' valign='top'>RADIO BUTTON</td></tr>
<tr><td><h4>DELETE QUESTION</h4></td><td><input type='checkbox' id='deleteQuestion' name='deleteQuestion' value='delete'/></td></tr>
<tr><td><h4>CHANGE QUESTIOn</h4></td></tr>
<tr><td><label>SLOVENIAN</label></td>
<td><input type='text' id='SloQuestion' name='SloQuestion' size='50' value ='Some question 2'></td></tr>
<tr><td>TYPE QUESTION </td><td><select id='typeQuestion' name='typeQuestion'><option value='text'>Text field</option>
<option value='textarea'>Textarea</option><option selected='selected' value='radio'>Radio</option></select></tr>
<tr><td></td><td><input type='text' id='RadioValue0' name='RadioValue10' size='50' value ='Bad'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue1' name='RadioValue11' size='50' value ='Sufficiently'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue2' name='RadioValue12' size='50' value ='Dobro'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue3' name='RadioValue13' size='50' value ='Excelent'></td></tr>
<tr><td></td><td><input type ='submit' id='submit' name='submit' value='Izvedi spremembe'/></td></tr>
</table>
</form>
Still editSurvey.php page (I have add two because I can't put all text just in one textarea)
<form id='updateQuestion3' name='updateQuestion3' method='post' action=''>
<input type='hidden' name='hidden' value='question3'/>
<table width='600px'><tr></tr>
<tr><td width='50%' valign='top'><label for='question3'><h2>CURRENT QUESTION:</h2></label></td></tr>
<tr><td>SLOVENIAN </td><td width='50%' valign='top'> <label for='question3'>Some question 3</label></td></tr>
<tr><td width='50%' valign='top'>TYPE QUESTION</td><td width='50%' valign='top'>RADIO BUTTON</td></tr>
<tr><td><h4>DELETE QUESTION</h4></td><td><input type='checkbox' id='deleteQuestion' name='deleteQuestion' value='delete'/></td></tr>
<tr><td><h4>CHANGE QUESTIOn</h4></td></tr>
<tr><td><label>SLOVENIAN</label></td><td><input type='text' id='SloQuestion' name='SloQuestion' size='50' value ='Some question 3'></td></tr>
<tr><td>TYPE QUESTION </td><td><select id='typeQuestion' name='typeQuestion'><option value='text'>Textfield</option>
TextareaRadio
And my handlesurvey.php file:
if(isset($_POST["hiddenUpdateQuestion"])){
$username = 'root';
$password='';
$hostname='localhost';
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Ni se mogoče povezati na MySQL");
$selcetedDB = mysql_select_db("amon_survey",$dbhandle);
mysql_query("set names 'utf8'");
// HERE I WILL ENTER LATER SOME QUERY
mysql_close($dbhandle);
}
In your handlesurvey.php:
if(isset($_POST["hidden"]))
{
$username = 'root';
$password='';
$hostname='localhost';
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Ni se mogoče povezati na MySQL");
$selcetedDB = mysql_select_db("amon_survey",$dbhandle);
mysql_query("set names 'utf8'");
if($_POST["hidden"]=='question1'){
//Here will be question1's query;
}
if($_POST["hidden"]=='question2'){
//Here will be question2's query;
}
}
I think it's self-explanatory, comment if something's unclear.
Edited:
Am sorry, the $_POST was getting the right values, so I assumed the jQuery did too. Please see the updated code below:
In makesurvey.php:
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
form_id = (this.id);
var SloQuestion =$("#"+form_id+" #SloQuestion").val(); // it's basically saying to fetch the input value of the submitted form
var typeQuestion=$("#"+form_id+" #typeQuestion").val();
var RadioValue1 =$("#"+form_id+" #RadioValue1").val();
var RadioValue2 =$("#"+form_id+" #RadioValue2").val();
var RadioValue3 =$("#"+form_id+" #RadioValue3").val();
var RadioValue4 =$("#"+form_id+" #RadioValue4").val();
alert(SloQuestion);
//If custom validation:
//if(form_id='updateQuestion1')
//{//validations for #updateQuestion1}
//if(form_id='updateQuestion2')
//{//validations for #updateQuestion2}
$.post( "handlesurvey.php", $("form").serialize())
.done(function( data ) {
alert("You have changed question!");
}); });
});
</script>
Edited (2nd time):
I'm guessing as per your comment below, you need to know whether the delete question checkbox is checked or not.
You can get to know through:
var delVal = $("#"+form_id+" #deleteQuestion ").is(':checked');
alert(delVal); //returns true if checked, false if not checked
A slight correction, please change your $.post to this so that it sends only the submitted form:
$.post( "handlesurvey.php", $("#"+form_id).serialize())
.done(function( data ) {
alert("You have changed question!");
});
And on your php:
if($_POST["hidden"]=='question1'){
if(isset($_POST["deleteQuestion"]) && ($_POST["deleteQuestion"]=="delete"))
{
//Your delete query for question1
}
}
if($_POST["hidden"]=='question2'){
if(isset($_POST["deleteQuestion"]) && ($_POST["deleteQuestion"]=="delete"))
{
//Your delete query for question2
}
}
You can use some common classes let say "form" for form tag and "input" for each input, textarea or radio. Then loop on each input element validate and send data.
This should be pretty generic:
$(".form").submit(function(){
var data = [];
var valid = true;
// get data & validate
$(this).find('.input').each(function () {
if ($(this).val().length)
data[] = $(this).val();
else
valid = false;
});
if (!valid)
// set some errors
return false;
// send form data ....
});
I am not going to give you the full answer but will guide you.
Step 1: Add a class to the form:
<form id='updateQuestion1' class="sq_form" name='updateQuestion1' method='post' action=''>
</form>
<form id='updateQuestion2' class="sq_form" name='updateQuestion1' method='post' action=''>
</form>
Step 2: bind onsubmit event to the form using the class selector
$(".sq_form").submit(function(event) {
var indata = $(this).serialize(); //the form data
//do whatever validations you need to do by using using this keyword
//Example: $(this).find('input')
});

Remove Respective Li from all

Following is my fiddle in which when user click on all delete then on foreach for LI function. I want to remove those lis which contains name like abc,def,ghk in their input field . I just want to know how to check that the active li on foreach loop contains the certain value that matches it input field value or not so i'll stop to remove it.
Fiddle: http://jsfiddle.net/mT5vw/2/
$(document).ready(function () {
$(document).on('click', '.liDelete', function () {
li = $(this).parent();
li.remove();
});
$("#butadd").click(function () {
$("ul").append("<li>Folder Name : <input type='text' class='fname' value='' required='required' /> <input type='button' class='liDelete' value='- Remove' /></li>");
});
});
function alldelete() {
$('#folder li').each(function (e) {});
}
If you want to remove the li that the input contains a value like ABC try:
$('#removeAll').click(function(){
$('#folder li input[type="text"]').each(function () {
if ($(this).val() === "abc") {
$(this).parent().remove();
}
});
here the jsfiddle only write abc in the input and before press remove all.
I've edited your fiddle: http://jsfiddle.net/mT5vw/3/
If this is what you what it can be achieved by, removing all elements from the tag and then reinserting one empty row.
js:
$(document).ready(function () {
$(document).on('click', '.liDelete',function() {
li = $(this).parent();
li.remove();
});
$("#butadd").click(function () {
$("ul").append("<li>Folder Name : <input type='text' class='fname' value='' required='required' /> <input type='button' class='liDelete' value='- Remove' /></li>");
});
$("#deleteall").click(function(){
$('#folder').html("<li>Folder Name : <input type='text' class='fname' value='' required='required' /> <input type='button' class='liDelete' value='- Remove' /></li>");
});
});

Append Jquery plugin to document

I am using a plugin called minicolors for jquery link. I am trying to appened a color picker here (in 2 places, a div and table just for testing) with a button click, it seems though that it only works on the second button click, the first simply returning an empty input box.
<script type="text/javascript">
function addPicker() {
$(document).ready( function() {
$(".colorpick").miniColors({
change: function(hex, rgb) {
}
});
});
var picker = "<input type= 'text' class='colorpick' size='6' autocomplete='on' maxlength='10' value='' />";
$("#datatable > tbody").append("<tr><td>"+picker+"</td></tr>");
$("#testdiv").append(picker);
}
</script>
<div id="testdiv"></div>
<button onclick =" addPicker();">Button</button>
No Idea why this is not working.
Try :
$(document).ready( function() {
$('.addButton').click(function(){
$("<input type= 'text' class='colorpick' size='6' autocomplete='on' maxlength='10' value='' />").appendTo("#datatable tbody").wrap('<tr><td></td></tr>');
$('.colorpick').miniColors();
});
});​
Live demo : http://jsfiddle.net/hCVpX/12/

Categories