How to change and add new HTML objects with Javascript? - php

I know a bit of PHP and so also HTML/CSS, and I have made a simple quiz program allowing users to create and do quizzes that are stored in a MySQL database. Now what I am trying to do is improve the usability and efficiency of the program.
On the createQuestions form, there are eight textboxes, users can fill in between 2 or 8 of these boxes with answers. Although I think this looks messy with all eight, and what I would like is to have 2 textboxes, and when there is text in the second one, the third one appears and so on.. up to eight
I spent a few hours learning a bit of basic JS, and managed to get it, so that there was a button that changed the visibility propities of the input box, label and radio button of each row. Although I wrote it really inefficiently lots of lines of code to do not much :p - giving each object a separate ID, and it still didn't work that well.
Below is an example of how my HTML is laid out, I have eight of these, though I could replace this with one, and a PHP for loop with a limit of 8.
<div id="c">
<p class="subFont" id="cT" style="display:none;">Answer 3</p>
<input type="text" name="optionC" class="textbox" style="display:none;" id="cI">
<input type="radio" name="correctAns" value="c" id="cR" style="display:none;">
<input type ="button" name="add" value="d" style="background-color:green;" onclick="addBox('d', 'inline')" id="cB" style="display:none;">
</div>
Any suggestions on how to write the script descried above? Please could you comment or briefly explain your workings, so I can learn from it :)
Thank you loads in advance, I'm so grateful to all you guys on stackoverflow ;)
ps, any suggestions for learning js resources?

Pure Javascript
to hide/show object id="cR"
// hide
document.getElementById('cR').style.display = 'none';
// show
document.getElementById('cR').style.display = 'block';
to append textarea to
document.getElementById('c').innerHTML += '<textarea name=".." id=".."></textarea>';
events:
<input type="text" id="xxx" onchange="your action here" />
jQuery
to hide/show object id="cR"
// hide
$('#cR').hide();
$('#cR').fadeIn(); // with fade in effect
// show
$('#cR').show();
$('#cR').fadeOut(); // width fade out effect
to append textarea to
$('#c').append('<textarea name=".." id=".."></textarea>');
events:
$('#xxx').change(function() {
your action here
});

another way to add element dynamically in page..
<html>
<head>
<script>
function addElement(obj) {
text_limit = 5; // limit text then add text after that.
var text_lenght = obj.value.length;
if(text_lenght >= text_limit){
var mainElement = document.getElementById('myDiv');
var counter= mainElement.getElementsByTagName('textarea').length;
var newTextArea = document.createElement('textarea');
var textareaname = 'txt_area'+counter;
newTextArea.setAttribute('id',textareaname );
newTextArea.onkeydown= function() {
addElement(this);
}
mainElement.appendChild(newTextArea);
}
}
</script>
</head>
<body>
<div id="myDiv">
<textarea id="txt_area2" onkeyup="addElement(this);"></textarea></div>
</body>
</html>

Related

Text box value instant show calling method

Script
<script type="text/javascript">
function KeyHandler() {
var result = document.getElementById('result');
result.innerHTML=document.getElementById('txtInput').value;
}
</script>
HTML
<input type="text" id="inputField" />
<div id="screen"></div>
This code work good in html but i want
<a href="#?call=limit.lim&height=400&width=400&id={$ID}&team=
{$Name}&val={'**********'}&name={$Name2}&catname={$Cat}"
class="inlinePopup" title="{'Namer'}">{$Single}</a>
val={'****'} What ever i type in the text box that's i want here in the star position how
val={'<div id="screen"></div>'} this not work
Example : type a value 123 in the text box means that's instant like
val = 123
You could change the href attribute of the link in your KeyHandler function.
For example:
function keyHandler(){
var inputText = document.getElementById('inputField').value;
document.getElementById('myLink').href = '#?yourParam=something&val='+encodeURIComponent(inputText);
}
Would work with the HTML:
<input type="text" id="inputField" onkeydown="keyHandler()" />
Link Text
Could you adapt this technique to suit your needs? Alternatively, could you provide more details about your problem? Example code, motivation, context etc?

How to get input value from html form in jQuery?

I want to ask how i can get value of input ONLY ON SUBMIT in Javascript from HTML form when i have many forms with same name on one page.
It's looking like this:
First printed HTML form:
<div id="addCommentContainer3">
<form class="add-comment-form" id="addCommentForm3" method="post" action="">
<input type="hidden" value="3" name="comentonpost" id="comentonpost"/>
<textarea class="commentinput" name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
Second printed:
<div id="addCommentContainer2">
<form class="add-comment-form" id="addCommentForm2" method="post" action="">
<input type="hidden" value="2" name="comentonpost" id="comentonpost"/>
<textarea class="commentinput" name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
And like this there are many more .
I must take the value of comentonpost because i need it in my Javascript so when i post comment it wil appear before addCommentContainer of the submited form.
And there is the whole Javascript:
$(document).ready(function(){
var name_element = document.getElementById('comentonpost');
var x = name_element.value;
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
/* Listening for the submit event of the form: */
$('#addCommentForm'+x).submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
$('#submit').val('Working..');
$('span.error').remove();
/* Sending the form fileds to submit.php: */
$.post('comment.submit.php',$(this).serialize(),function(msg){
working = false;
$('#submit').val('Submit');
/*
/ If the insert was successful, add the comment
/ below the last one on the page with a slideDown effect
/*/
$(msg.html).hide().insertBefore('#addCommentContainer'+x).slideDown();
},'json');
});
});
And in this way when i press the Submit button it's working only for the first form printed in the page.
My question is how i can fix this? How i can make it get the comentonpost value only of the submited form not the first printed, is there any better way this script may work?
Thanks in advance!
This will do what you need:
$(document).ready(function(){
/* Watch OnSubmit for all forms */
$('form').submit(function(e){
e.preventDefault();
/* Show the 'commentonpost' for the submitted form */
alert($(this).children('#comentonpost').val());
});
});
This works, but you should keep in mind that your document is not valid because you have elements that have the same IDs. IDs must be unique within a document for it to be valid.
You may only need to change this part:
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
/* Listening for the submit event on all the forms: */
$('form[id^=addCommentForm]').on('submit', (function(e) {
var submitted_form = $(this);
//etc...
when you use jquery to select an ID, it will return 0 or one elements that match, and it will match the first one it finds. from http://api.jquery.com/id-selector/
Calling jQuery() (or $()) with an id selector as its argument will
return a jQuery object containing a collection of either zero or one
DOM element.
whenever you use $("#submit") its parsing through the DOM and finding the first instance of <input type="submit" id="submit" value="Submit" /> and returning that element. what you really want to do in your to scope your search down. you know you want the input from the form that was submitted, so you should try
$(this).find("#submit")
this will start at the form element, and search only elements contained inside the form for the first element with an ID of submit.
update
didnt realize your event was only tied to the first form, this whole things needs some work.
you've got a generic form template, and when you've got multiple forms like this, you really shouldnt be giving them all the same ID. instead, start binding event handlers to classes, and use the dom to store whether a form is 'working' or not as well
http://jsfiddle.net/neKdz/3/
I would suggest something like this
$(document).ready(function(){
$(".add-comment-form").submit(function(e){
var x = $(this).find("#comentonpost").eq(0).val();
// now you have number x of submitted form and you can do the rest
});
});
Edit:
To prevent page reloading because of form submission, add onSubmit="return false;" on form elements, e.g.:
<form class="add-comment-form" id="addCommentForm3" method="post" action="" onSubmit="return false;" >
But because of this we have to follow another approach using click event:
$(document).ready(function(){
$("#submit").click(function(e){
var x = $(this).parent(".add-comment-form").eq(0).find("#comentonpost").eq(0).val();
// now you have number x of submitted form and you can do the rest
});
});
Combination of click event and cancelling submit event should work. But just for the record (you should already know this, but I can imagine you might have a reason for doing it) using same id on multiple html elements is not a good strategy.

Passing checkbox checked from jQuery to PHP in CodeIgniter

I'm working on a PHP self-evaluation form that has 5 question categories with 10 questions each. In the beginning of the application, I have 5 checkboxes to represent these categories, and they are automatically checked. The idea is that whenever user unchecks a category, the questions of that category instantly disappear from the form, and when they check it again, they come back. Something that should be achievable with the help of jQuery and AJAX.
I made the checkboxes with CodeIgniter's form_helper:
for($i = 1; $i<=5; $i++) {
$this->formapp_model->printCatName($i);
$data = array('name'=>'category$i', 'id'=>'category$i', 'value'=>'$i', 'checked'=>TRUE);
echo form_checkbox($data);
}
And I have a function to printing all 10 questions of the category from database after their category id, which works fine when I just post them as they are:
$this->formapp_model->printCategory(1);
$this->formapp_model->printCategory(2);
$this->formapp_model->printCategory(3);
$this->formapp_model->printCategory(4);
$this->formapp_model->printCategory(5);
Using the help of this:
Passing whether a checkbox is checked, via jQuery, to PHP
I was able to gather that for the jQuery, I need something like
var category1 = $('#category1:checked').val();
in order to check if the checkbox has been selected. I also tried
var category1 = $('#category1:checked').post();
as it seemed logical to use post in order to PHP to recognize it.
And for the print selection something like
if (isset($_POST['category 1'])) { $this->formapp_model->printCategory(1); } else { echo "This category is not selected."; }
I tried this, but PHP doesn't recognize the message that jQuery is giving it, meaning the category's questions disappeared permanently, whether the checkbox was checked or not. I checked with echo var_export($_POST); and noticed that all the jQuery is printing out is: array ( ). The question mentioned above was very informative, but missed some info that I would have needed to get it to work. The asker was also using an array instead of separate variables so I don't know how to edit it properly.
I'm a complete newbie with jQuery and AJAX so I have a hard time grasping what I need in order to get jQuery and PHP communicate dynamically the way I described. I have run around stackoverflow to find similar cases, but none of them have quite had what I need. However, I deeply apologize in case this is a repeativive question. Thank you to anyone who helps!
PHP is server side, you need the questions to appear/disappear client side meaning you want to make that happen using jQuery itself (or regular js but since you're already loading jQuery it's quicker just to use the library itself).
To be honest I'm not really following how your view is working so I'll just give some basic code to give you the idea. You create the checkboxes and the questions giving each a unique ID. Then in the on click method for the check boxes you determine which questions to show.
HTML:
<div id="checkboxes">
<input type="checkbox" id="box1" class="check" checked="checked"/>
<input type="checkbox" id="box2" class="check" checked="checked" />
<input type="checkbox" id="box3" class="check" checked="checked" />
<input type="checkbox" id="box4" class="check" checked="checked" />
<input type="checkbox" id="box5" class="check" checked="checked" />
</div>
<div id="question1" class="question">
<p>Question 1</p>
</div>
<div id="question2" class="question">
<p>Question 2</p>
</div>
<div id="question3" class="question">
<p>Question 3</p>
</div>
<div id="question4" class="question">
<p>Question 4</p>
</div>
<div id="question5" class="question">
<p>Question 5</p>
</div>
jQuery:
$(".check").on("click",function(){
var id = $(this).attr("id");
var id2 = id.substr(id.length -1);
var question = "question"+id2;
if($(this).is(":checked"))
{
$("#"+question).css("display","block");
} else {
$("#"+question).css("display","none");
}
});
Demo: http://jsfiddle.net/calder12/taSPX/1

Show one row of data, click next, hide original row and show next row... and so on

I'm using the http://www.advancedcustomfields.com plugin to create custom fields in Wordpress. I'm specifically using the repeater field functionality.
On a page I have a repeater that has an unlimited amount of rows. The usual way of echoing out all the data is the following:
<?php $counter = 1; if(get_field('step_by_step_training')): ?>
<?php while(the_repeater_field('step_by_step_training')): ?>
<p class="training-<?php echo $counter; ?>"><?php the_sub_field('introduction'); ?></p>
<?php $counter++; endwhile; ?>
<?php endif; ?>
Is it possible to show one row of data at a time with a next button that when pressed will show the next row of data? I only want one row of data showing at a time so if row 1 is originally showing, when next is clicked it hides row 1 and shows row 2. Essentially creating a step by step process.
Eventually I'd like to include a form so the user can submit data.
UPDATE:
<form class="form" method="POST" action="<?php the_permalink(); ?>">
<?php $counter = 1; if(get_field('step_by_step_training')): ?>
<?php while(the_repeater_field('step_by_step_training')): ?>
<div class="form-row">
<p class="training"><?php echo the_sub_field('introduction'); ?></p>
<button class="next">Next Form Element</button>
</div>
<?php $counter++; endwhile; ?>
<?php endif; ?>
</form>
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function() {
// hide all form-rows, but not the first one
$('.form-row').not(':first').hide();
$('button.next').click(function(e) {
// prevent the next buttons from submitting the form
e.preventDefault();
// hide this form-row, and show the next one
$(this).parent('div.form-row').hide().next('div.form-row').show();
});
});
});
</script>
You could do something simple like this using jQuery (I think this is what you wanted?):
$(document).ready(function() {
// prepend a 'previous' button to all form-rows except the first
$('<button>').addClass('previous').text('Previous').prependTo($('.form-row').not(':first'));
// hide all form-rows, but not the first one
$('.form-row').not(':first').hide();
// add the submit button to the last form-row
$('<input>').prop('type', 'submit').val('Submit Form').appendTo($('.form-row:last'));
// handle the previous button, we need to use 'on' here as the
// previous buttons don't exist in the dom at page load
$('.form-row').on('click', 'button.previous', function(e) {
e.preventDefault();
$(this).parent('div.form-row').hide().prev('div.form-row').show();
});
$('button.next').click(function(e) {
// prevent the next buttons from submitting the form
e.preventDefault();
// hide this form-row, and show the next one
$(this).parent('div.form-row').hide().next('div.form-row').show();
});
});
some example markup:
<form action="index.php" method="post">
<div class="form-row">
<label for="forename">Forename</label>
<input type="text" name="forename" />
<button class="next">Next Form Element</button>
</div>
<div class="form-row">
<label for="forename">Surname</label>
<input type="text" name="surname" />
<div style="clear: both;"></div>
<label for="another">Another</label>
<input type="text" name="another" />
<button class="next">Next Form Element</button>
</div>
<div class="form-row">
<label for="last">Last Form Element</label>
<input type="text" name="last" />
</div>
</form>
You can add as many form elements to each form-row as you want, here's a fiddle to play with
edit
Things to note here are that the previous buttons are injected to the DOM dynamically, and so is the forms submit button (notice how I've removed it from the last form-row in the markup)
Here's an updated fiddle
You could start with a jQuery accordion menu. Some CSS will allow you to minimize the real estate occupied by the deselected rows. If you want to actually discard and retrieve certain rows based on some identifiable characteristic (for instance, ID number), you'll need to go with AJAX.
You could write your own custom method with something like JQuery.
Assign a class to each row, and keep track of which one is selected, when viewing another row simply .hide() the one that was showing and .show() the one you wish to display.
If you want to keep your HTML cleaner, you could use the JQuery .data() functionality to assign identifiers to each element and refer to them that way as well.
Most of this all depends on your constraints with wordpress, how it looks & your actual HTML layout
After it's all written to the screen, can't you just hide everything but the first row? And then each time you click the button, have it hide everything and show the next row. Try using jquery's next() function. jquery - next()
Ah, looks like deifwud beat me to it with a better explanation.

Questions regarding forms and php (clearing form, live refresh, multiline)

I have several questions regarding forms and PHP but if I should put them into different posts then I will.
Here is my form code:
<form id="t-form" name="tForm" action="translate.php" method="POST">
<div id="t-bar">
<div class="t-select">
<select name="start-lang" id="choice-button">
<option value="english">English</option>
</select>
<label>into</label>
<select name="end-lang" id="choice-button" onChange="document.forms['tForm'].submit();">
<option value="caps"<?php if ($resLang == 'caps') echo ' selected="selected"'; ?>>CAPS</option>
<option value="lowercase"<?php if ($resLang == 'lowercase') echo ' selected="selected"'; ?>>lowercase</option>
</select>
<input type="submit" id="t-submit" value="Translate">
</div>
</div>
<div id="t-main">
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onChange="document.forms['tForm'].submit();"><?php echo $source; ?></textarea>
<input type="button" id="t-clear" onclick="this.form.elements['t-src'].value=''">
<textarea id="txt-result" name="txt-result" readonly disabled="disabled" placeholder="result..."><?php echo $result; ?></textarea>
<input type="button" id="t-copy" name="t-copy">
</div>
</form>
Question 1: I currently have onclick="this.form.elements['t-src'].value=''" which clears one textbox when the button is pressed. Is it possible to have the same attribute clear both textareas in my form? I can't seem to find an answer anywhere for clearing 2 elements with 1 button. I do not want to clear the form as I would like to keep the selected dropdown values so that is why I'm doing it this way.
Question 2: How would I go about implementing a live refresh of the results textarea so they user can simply type and see the result? I've look at the ajax and jquery required and am confused as most don't show how to output to a form element and only to a div. (Similar to google's translate)
Question 3: I realized that if a user does a new line in the textarea, when they submit for translate, it gives them a php header error. Any ideas how I can avoid this? This is my header for the translate.php file used in the form:
header("location: /?txt-result=$result&t-src=$textSource&end-lang=$outputLang");
I am merely trying to do this as a learning excersise and would really appreciate any guidance or answers to the three questions. Many thanks for your help!
question 1
you should have:
onclick="clearTextboxes();"
and in javascript something like:
//if you want to delete all the inputs that are of type text
function clearTextboxes(){
var inputs = document.getElementById('t-form').getElementsByTagName('input');
for (var control in inputs){
if(inputs[control].getAttribute('type') == 'text'){
inputs[control].value = '';
}
}
}
question 2
it is far too broad to put here as an answer, you should really look at jQuery's $.ajax, and create a different question with specific doubts.
question 3
use the PHP urlencode() function
Answer 1: Have your onclick event call a function which clears those values for you:
<script type="text/JavaScript">
function clearTextareas()
{
this.form.elements["t-src"].value = "";
this.form.elements["txt-result"].value = "";
}
</script>
<input type="button" id="t-clear" onclick="clearTextareas()">
Answer 2: Add an onkeydown event in the source textarea that peforms the translation (or whatever it needs to do) and then puts the result in the result textarea:
<script type="text/JavaScript">
function translateText()
{
var text = this.form.elements["t-src"].value;
// do something
this.form.elements["txt-result"].value = text;
}
</script>
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onkeydown="translateText()"><?php echo $source; ?></textarea>
Answer 3: Perhaps an onsubmit event in the form element that will sanitize the input from the text area. Have a look at JavaScript's encodeURIComponent. Perhaps this will work for you:
<script type="text/JavaScript">
function sanitize()
{
this.form.elements["t-src"].value = encodeURIComponent(this.form.elements["t-src"].value);
}
</script>

Categories