New Text field when Button is clicked - javascript

I have a problem that hopefully someone can help me with. I have a webpage I've been building with html and php that has text fields that you fill out and submit to create an evaluation. What I would like to do is be able to click the Add Another Criteria button to add another criteria name and description field to the page and the Add criteria and create buttons would then go below the newest set of text fields created.
All this information is going to be stored in a database using PHP controller files so I am not sure if using Javascript would be the best way to achieve my goal. I apologize for my lack of php knowledge I am very new to this any help would be much appreciated Thank you!

This would be easier if you're using jQuery, but without, it's still possible.
var newCriteria = document.createElement("input");
newCriteria.setAttribute('placeholder', 'Criteria Name');
newCriteria.name = 'criteria[]';
var newDesc = document.createElement("textarea");
newDesc.setAttribute('placeholder', 'Description');
newDesc.name = 'description[]';
document.getElementById("theForm").appendChild(newCriteria);
document.getElementById("theForm").appendChild(newDesc);
On the PHP side, using the brackets will make the value come through as an array:
for ($x = 0; $x < $_POST['criteria']; $x++) {
// do something with each $_POST['criteria'][$x] and $_POST['description'][$x]
}

Use jQuery to add an onClick Listener and add the fields:
$("#button").on("click", function() {
$("#containertoappend").append('<input type="text" id="anothercriteria" placeholder="Another criteria">');
$("#containertoappend").append('<textarea id="anotherdescription" placeholder="Another Description"></textarea>');
});

Related

How to get path of button located in table cells

I am working on one table, where I have created one button which I am using in different rows and tables based on some condition.
I have one scenario where I need to show the button to some specific users, I have implemented the condition however I am not able get the path of the button, I can hide the cell but in that case complete cell is removed from the table which is not looking good, please help me to get the path of the button, so that I can hide it, here is the code I am using:
totalrows = document.getElementById("DEVmyTable").rows.length;
for(i = 0;i<totalrows; i++){
if(actualusernamevalue == currentusernamevalue){
table.rows[i].cells[6].style.display = "";
}
if(actualusernamevalue != currentusernamevalue){
table.rows[i].cells[6].style.display = "none";
}
}
Here in Cells[6] my button is present which I am created dynamically like this:
row = document.getElementById("DEVFirstrow");
var w = row.insertCell(6);
w.innerHTML = '<button onclick="Releaseentry(this)"type="button"
id="release" class="btn btn-primary release">Release</button>';
I have not added the complete code here, but based on the ids I am using this code in different table and rows.
in this code I have hidden the cell, for hiding the button I am not able to get the path, and that is what I am looking for.
You actually style the cell based on table.rows[i].cells[6].style.display and not its content. You choose the 6th cell and style it.Another mistake you make is that you use id in the button while the button is used in multiple rows which makes the id useless as it should be unique.
What I would do is simply use the class of the buttons and then based on the checks you have decide what the button should do using jquery, so:
if(actualusernamevalue == currentusernamevalue){
$('.release').show();
}
if(actualusernamevalue != currentusernamevalue){
$('.release').hide();
}
If I understand well what you are trying to do at least. The simpler solution, the better solution!
EDIT: By the way, you should keep in mind that if someone wants to find the button when you play with the display property in both ways, they can always find it through the source code. If someone inspects the element and changes the CSS manually they will be able to see the button, so it's always important to have back end validation too for cases like this.
I think I have got my solution finally, Thanks #natan for your help.
table.rows[i].cells[6].getElementsByTagName('button')[0].style.display = "none";
table.rows[i].cells[6].getElementsByTagName('button')[0].style.display = "";
I should have used this code.

Need to check value of hidden input field related to clicked element (multiple with same name)

Title isn't that clear, so let me see if I can explain what I'm doing.
I'm listing off users' posts, and have a like/comment button with those posts.
What I need to do, is capture when the like button is clicked (<span> tags), and then grab the post id from the hidden input field, and use that to post to the PHP script.
The PHP is doing all of the checking for if they're friends, privacy level is correct, etc. before actually submitting the like to the database, but I am currently just having the javascript/jquery be generated when the post is shown (naming each js variable/DOM element according to post id), but that's not very efficient and looks messy when viewing the source (But, it's the only way I can get it to work).
I want to be able to use an external javascript file to check when just the like button is clicked, and know what post that is being liked, and work that way.
I've been looking into this for quite some time, and it's to my understanding that this might work, but I have had no luck. I'm generating multiple posts on one page using foreach() loop, so the names/ids/classes of the elements are the same.
For a little better understanding, here's an example of what a post might look like:
<div class="feedPost">
<img src="#" class="feedProfile"/>
FirstName LastName
<div class="feedPostBody">Hello, world!</div>
<input type="hidden" value="24772" name="feedPostID">
<span class="feedLikeButton">Like</span> | Comment | 2 mins ago
</div>
and, using javascript/jquery, I want to be able to do something like this in an external js file:
$('.feedLikeButton').on('click',function(){
var post_id = 0; //I need to get the ID from the post that the like button is related to.
//If I just did $('.feedPostID').val() it wouldn't work
$.post("https://mysite/path/to/like.php", {post: post_id}).done(function(data){
if(data == "success"){
//This will set text from "Like" to "Unlike"
//Again, I can't just do $('.feedLikeButton') to access
//I guess I could do this.innerHTML? Would still need to access feed post id
} else {
//Probably will just flash error to user if error, or something similar
}
});
});
You should get the like button
var likeButton = $(this);
Then get it's container
var container = likeButton.parent();
Then find the hidden field
var idInput = container.find('[name="feedPostID"]');
Then get it's value:
var id = idInput.val();
With all these references you can do whatever you want.

Moving a value into an html form field

I am very new to JavaScript and would like to know how to go about the following.
I have a form that I am using for entry to a fishing contest.
It contains fields for up to six anglers but they only fill out two.
What I am attempting to do is where a contest is declared via the form I add a value (the entry fee) to a hidden field on the form.
Like:
if form.anglername1 <> "" then form.angler1fee = "75"
Have tried various methods I have seen on the web without success.
Having said that I really don't know what I am doing.
Have been a Clarion coder for too many years to talk about and am finding JavaScript just a little tough.
If anyone can help a little I would be very happy.
Without seeing more code, I'm not sure exactly how to do what you want, but the snippet you gave isn't JavaScript. Here is the proper JS syntax for what you have written.
if(form.anglename1 != ""){
form.anglerfee = "75";
}
why to add an hidden field? try this with your input field:
<input name="anglername1" onblur="this.value=this.value==''?'75':this.value;"
onfocus="this.value = this.value == this.defaultValue? '' : this.value;" />
HTH !

PHP Form: One to many UI relationships, represented in Javascript/jQuery?

I have a simple problem, but for some reason cannot figure out the words to find a solution (or which I'm sure there are many). I'm building a simple PHP form for a user, who may have zero-to-infinite phone numbers and one-to-infinite email-addresses.
I want one PHP page which allows me to click a button like "add new phone number" and another phone number field pops up. Next to each field should be a delete icon which removes that row. When I submit the form I want to be able to process it in PHP, ideally in a simple way.
The problem is I'm manually writing out the jQuery line-by-line and trying to build a framework to make it so I can easily apply this to other fields. Then I realized it must have been done already, and I'm reinventing the wheel.
Does anyone know of any simple one-to-many tools to spare me reinventing the wheel?
UPDATE Turns out I should have been searching for "form element repeater" or "form input cloning" or some similar phrase, instead of "jquery one to many inputs". The new phrases yielded the results found in my accepted (my own) answer.
Two frameworks:
SheepIt: http://www.mdelrosso.com/sheepit/index.php?lng=en_GB&sec=home
jQuery Form Element Repeater Plugin: https://github.com/cballou/jQuery-Form-Element-Repeater-Plugin
$('.add-input').click(function(){
var num = $(this).attr('data-num'),
$newInput = $('<input data-input="' + num + '" type="tel"/>'),
$delete = $('<a class='delete'/>');
$delete.on('click', function(ev){
$newInput.remove();
});
$('#formName').append($newInput + $delete);
}) ;
Something along the lines of this should work fine. It generates a input and delete button attaching a click event to the delete button generated and uses data attributes so you can keep track of inputs through PHP.
Your html code should look like this <input name="phonenumber[]">
Your jquery code will look like this
$('#add_phonenumber').click(function(){
$('#my_form').append('<input name="phonenumber[]">'); //add
});
$('.delete_me').click(function(){
$(this).closest('span or div').find('input').remove(); // delete (NOTE: your delete button and an input must be in one container for each input)
});
<span class="inputs"><input type="text" name="phonenumber[]"><a class="delete_me">delete this input</a></span>
Your php form handler
$new = array();
$phones = $_POST['phonenumber'];
$count = count( $phones );
for ( $i = 0; $i < $count; $i++ ) {
if ( $phones[$i] != '' ) :
$new[$i]['phonenumber'] = stripslashes( strip_tags( $phones[$i] ) );
endif;
}
// now array $new contains your phone numbers, you can save it or whatever you want to do with it
As a simple alternative maybe you could have one input box and separate the multiple entries with semi-colons or some other marker. Then in the php script you could use the explode function to separate them out into an array. e.g. :
johndoe#gahoo.com; janedoe#gahoo.com;jamesdoe#gahoo.com;
This would allow cut and paste of e.g. strings of email addresses, so for some applications it might be a preferable solution, as well as requiring minimal coding

cakephp - Javascript

We are working on an application using the CakePHP framework
Basically, its a questionnaire application and it has a few dependant questions, i.e. based on a response to a specific question, it needs to show or hide the next one
For e.g.
Question: Are you married? Yes/No
If the user selects Yes, then using javascript the next question gets displayed for user input
Question: Spouse's name
Saving this information is fine, but when editing, when populating the form, we would want to be able to display the fields for which user has inputted data - in this case, it needs to show the field that has the spouse's name
Since by default we are hiding the spouse name field, when editing, it doesn’t display the field, even though there is a value to it
Is there some way that CakePHP can handle this or does it require us to write some javascript to take care of this?
Thanks in advance.
CakePHP does not manage this for you. While CakePHP is very powerful and a great framework, it will not write this kind of logic for you. You must write it.
I would suggest making the EDIT screen different from the ADD screen. Build the list of values from the database and display the fields that have values (and include any empty fields that should require values).
Keep in mind reusable does not necessarily mean that all CRUD actions fit into the same view.
Like others I advise you use differents EDIT and ADD screens.
But you can try make it with Javascript like this:
<script>
function enableDisableField(targetFieldId){
var targetField = document.getElementById(targetFieldId);
var checkbox = event.target;
console.log(checkbox.checked);
if (checkbox.checked){
targetField.disabled = false;
targetField.value = "empyt";
}else{
targetField.disabled = true;
targetField.value = "empyt";
}
}
</script>
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, 'disabled']); ?>
It works well for ADD, but if you and EDIT you have to change de disable value according a field value:
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, !isset($user->married) ? 'disabled' : '' ]); ?>

Categories

Resources