I have a dropdown in my form which actually helps generate mysql db queries on the fly based on the query type .
e.g if my querytype in the dropdown in fetchYourDetails , then a text box will appear in the form which will ask for my name . Once , I enter my name and click on generate , it will frame the query and run it in the background php.
Like this I have around 4/5 query types and it's likely to increase in the future. Here I have a problem with my current implementation .
What I'm presently using is : a form where I have the dropdown and all the parameter fields (hidden) to start off with . Now, with the onchange() function in my js , I will show some specific parameter rows based on the dropdown option selected and hide the rest.
so here's how my HTML code looks like :
<form>
<table>
<tr id='dropdown'>
<td>
<select id='select_options' onchange ="javascript:updateCustomQueryFields();">
<option value='getyourdetails'></option>
<option value='getyourbikedetails'></option>
<!-- so on -->
</select>
</td>
</tr>
<tr style='display:none'>
<td>
<!-- one field -->
<!-- create the generate option -->
</td>
</tr>
<tr style='display:none'>
<td>
<!-- one field -->
<!-- create the generate option -->
</td>
</tr>
<!-- so on -->
</table>
</form>
and my onchange function looks like :
function updateCustomQueryFields()
{
val=$('#select_options').val();
//hideallfieldsfirst
if(val=='getyourdetails')
{
//show one field
}
else if(val=='getyourbikedetails')
{
//show one field
}
}
so far so good , now , when I click on generate option , it will execute the query and fetch the data from the db and display it in a results div below the form.
So, at the time of displaying results also, I have to hide some fields and display others in the view , based on the parameters set in the controller.
So the series of if-else statements are likely to increase there as well , when we add some more parameters .
So what I want is some mechanism by which we will generate the parameter fields on the fly , e.g , if the query type is 'getyourdetails' , only the name field should be created and rest all fields should be removed in the backend onchange function .
So how can that be achieved using jquery ? and will it be a proper methodology to implement the scenario what I want ? I have to keep in mind the propulating of my parameter fields once the call returns from the controller after fetching the results.
I'm not sure that I understood your question but at least my knowledge about your request says for making these kinds of forms it's better to use remove and append functions of jQuery. You can create any control dynamically and set them under control by the ID that you set for them. It's easy as drinking a glass of water!
Remove, Append
Correct me if my answer is wrong.
Related
I'm new to Yii framework and I'm designing a form (I'm using create form) to create a row in database.
Let me explain about the scenario succintly, so that I can make it clear for what I want-
I have 10 fields in this form. Out of this 10 fields, five fields change dynamically.
I created two div's basically div A and div B and repeated the fields as required for the two cases.
Say some fields which are textfields in div A will be dropdownlists in div B.
<div id="A">
<?php echo $form->labelEx($model,'selectionList'); ?>
<?php echo $form->textArea($model,'selectionList',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'selectionList'); ?>
</div>
<div id="B">
<?php echo $form->labelEx($model,'selectionList'); ?>
<?php echo $form->dropdownList($model,'selectionList',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'selectionList'); ?>
</div>
I have two radiobuttons say Single and Multi. When I select Single radiobutton, div A should be considered and div B discarded and when I select Multi, vice versa should happen.
So, is this the right way to change the form fields dynamically. Or else how can I do this using Ajax validation.
Not so related to question:
1) You are using same name for all fields, so only last one will be submitted (check generated html, name is MyModel[selectionList] and not MyModel[][selectionList]
2) You will have lots of problems with Ajax validation and dynamic fields (generated via js), since CActiveForm will generate js code via php.
Related to question:
3) To use one or another field, i suggest you to have two separate field names and just hide with js/css one, that is not needed right now. After submitting, just check value of radio button and decide what fields will be saved.
To validate these inputs, you have to use model scenarios (will define in rules what to validate and what not to):
$model = MyModel();
if ($_POST['C'] == 'multi') {
$model->scenario = 'validateOnlyFirstField';
} else {
$model->scenario = 'validateOnlySecondField';
}
Also you can use second CActiveForm.validate() parameter to define what attributes to validate.
Overview:
I am creating a dynamic web invoicing system,
Most of the page are textareas and I have used tables to nest as they will post data into seperate tables after the form is submitted. When the "Nested" Add a Row is selected, it should add a row inside with form field that has details on which row and which position so it can be gathered in a for loop when it is posted.
Image:
Problem:
Adding a row in the circled area does not add it in the last row, It add's it as it is in the image. Additionally it only works on the first item, the second add a row does not even register a click.
I am unsure how to get the variables to create the form name[][] in this particular index size and the parents index number (located in javascript line 2-3)
Relevent Code:
Javascript
$("#additemrow").click(function(){
var currentListItem = $(this).length;
var currentJobItem = $(this).parents('#items').index('#items');
currentListItem++;
$("#listitem:last").after(/*Blank Form Row*/);
bind();
})
PHP
<table id="items">
<tr class="item-row"><td>/*form elements*/</td></tr>
<tr class="list-row">
<td colspan=5>
<table class="itemlist">
<?php
$itemCount = 0;
foreach($jobListItem as $items) {
foreach($items as $item) {
if($problem['item_id'] == $item['item_id']) {
?>
<tr id="listitem">
<td class="list-item">
<div class="delete-wpr">
<textarea class="item" name="item[/*A PARENT ITEM NUMBER*/][<?php echo $itemCount;?>][item]"></textarea>
<a class="deleteitem" href="javascript:;" title="Remove row">X</a>
</div>
</td>
</tr>
<?php
}
$itemCount++;
}
}
?>
<tr>
<td colspan="5"><a id="additemrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
</table>
//NEXT ITEMLIST GOES HERE
</table>
EDIT: Foreach Loop is just used to get variables from a array.
Please let me know if you need more details or bits of code as im not sure if I have given enough information.
Regarding the problem where your row gets insertet at the top:
Like Bertrand Lefort already said: in JQuery you can append nodes to the end of another (parent) node by calling parent_node.append(child_node) (more information here)
You can also add elements before/after another element by calling another_element.before(element) / another_element.after(element) or (be aware of reversed syntax!) element.insertBefore(another_element) / element.insertAfter(another_element)
Regarding the problem where only the first "add a row" registers a click:
You're selecting by id. Id's are (or should be) unique, so when you call $("#additemrow").click(function(){ ... }) the onClick-function will only be attached to the first element that matches the given id (as far as I remember).
If you want to attach the same onClick-function to multiple elements use class instead. However, if you do so, you got to make sure you insert the new element relative to the clicked element (eg. by using .parent(), .siblings() or similar functions).
Regarding your problem #2, I don't really know what you're trying to do, but this is what I noticed:
currentListItem and currentJobItem seem to be unused in their scope, since you are declaring them as local variables but not using them
.parents('#items').index('#items') is redundant because .parents('#items') already selects only the parent elements that match '#items'. If you want to get the index of the matched element, use index() (without parameters, see jquery API for more)
Some other notes:
If you have the time (and the need of a clean project) I recommend using template engines like Smarty to separate your logic from the output. This improves the readability of your code and also makes it easier to find/eliminate bugs.
I hope this helped a little bit. If you provide more information on what you're trying to do and what doesn't work as you expext, I will try to provide further help and update my answer.
You could add an id to the parent html element, then in your click handler:
$("#additemrow").click(function(){
$("#parent").append(/*Blank Form Row*/);
})
<?php
$sort=$_REQUEST['sortby'];
echo" $sort ";
?>
<html>
<head>
</head>
<body>
<form method="get" id="thisForm" >
<table border=1>
<tr>
<td>
Day
</td>
<td>
Server
</td>
<td>
Service
</td>
<td>
Count
</td>
</tr>
</table>
<input type="hidden" name="sortby" id="sortby"/>
</form>
</body>
<script type="text/javascript" >
var sortArray=new Array("say","server","service","count");
function sorting( cnt)
{
alert(sortArray[cnt]);
document.getElementById("sortby").value=sortArray[cnt];
}
Based on the Header clicked i am trying to build a sort query but after it is submitted on clicking the "a href" link i am unable to get the hidden field posted data ?
I have changed "a href" to submit buttons then how do you stop the page being submitted if we click the same "sort by" link.
Here is what you're missing:
A link does not submit the form with input data, it just changes the url.
Submit the form.
Override the default <a> behavior (for example, using return false).
An updated version of sorting:
var sortArray=new Array("say","server","service","count");
function sorting(cnt)
{
document.getElementById("sortby").value = sortArray[cnt];
document.getElementById("thisForm").submit();
return false;
}
You can call it using:
Day
Working example: http://jsbin.com/ukoton/3
Another option is to use the popular library jQuery, which can greatly simplify your code:
$(function(){
$('#thisForm a').click(function(ev){
var sortValue = this.name;
// an alternative to this.name is to use a data-sortBy='day' attribute,
// and then $(this).data('sortBy')
$('#sortby').val(sortValue);
$('#thisForm').submit();
ev.preventDefault();
});
});
Working example: http://jsbin.com/ukoton/4
By default, anchor tags (that being A) do not submit a form. You can either use a button or submit the form using javascript.
You can submit the form from javascript with document.thisForm.submit()
Hmm .. I am not a php guy .. so I guess that initial 4 lines tries to get the sortby field from the form, anyways href link is not equivalent to html form submit, you will need to explicitly submit the form, maybe using javascript, to get the value
Just use a Submit button and style it to look like a link, if you need to. Using Javascript shouldn't be needed here.
Using an actual link instead of a Submit button will make the form unusable for people without javascript. That might include people using accessibility tools. Apart from that, it makes your page more complex (adding illogical HTML, and requiring Javascript), and therefore more complex to maintain.
I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill
What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps
This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>
You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.
if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want
I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!
I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)
I have web page in PHP which displays all records in a table. I want to add check boxes against all rows and user can check a check box to select a row and then submit the page. When the page is submitted I want to enumerate all check boxes and check whether they are checked or not, How can I do this?
You'll create your checkboxes like this:
<input name="rows[]" value="uniqueIdForThisRow" type="checkbox" />
<input name="rows[]" value="anotherId" type="checkbox" />
Then you can loop through them like this:
<?php
// $_POST['rows'] contains the values of all checked checkboxes, like:
// array('uniqueIdForThisRow', 'anotherId', ...)
foreach ($_POST['rows'] as $row) {
if ($row == 'uniqueIdForThisRow') {
// do something
}
}
?>
PHP docs on dealing with forms, see especially Example #3.
Creating the form
You can generate the HTML as follows:
<form [action, method etc]>
<table>
<?php
foreach($dataSet as $dataRow) :
?>
<tr>
<td>
<input type="checkbox" name="dataRow[]" value="<?=$dataRow['id']?>"/>
</td>
[Additional details about datarow here]
<tr>
<?php
endforeach;
?>
</table>
</form>
AFTER POST
look into $_POST['dataRow'] : this will be an array with values the IDS of your $dataRow, so using array_values on $_POST['dataRow'] will give you all the ids of the selected rows:
<?php
$checkedRows = array_values($_POST['dataRow']);
foreach($checkedRows as $row) {
// Do whatever you want to do with the selected row
}
You don’t have to check all checkboxes if they have been checked. Because only successful controls are send to the server. And a checkbox is only successful when it’s checked:
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
So you just have to look what checkboxes you get in the request at all. And if you want to use <select multiple>, take a look at How do I get all the results from a select multiple HTML tag? in the PHP FAQ.
if i were you... i wouldn't fight with altering html table structure.
you can handle that with Javascript frameworks like JQuery which is very effective solution for you. you deal only a few lines of JS code and you don't need exaggerate the html output (i guess it's probably long enough). about jquery there is a good source named visual jquery if you have never used that.
here is the way how to do that.
you dont need to edit inside the loop. you just only put an id to your table tag.
then add new column to your table with checkboxes inside.
then you can get the values of checkboxes & serialize them in to a hidden input. or you can handle selected rows with ajax easy. i think JS framework will work better.
normally i've added many links to post but it says it's not allowed for new users.