javascript not functioning in Wordpress - javascript

So basically I made a custom page template in wordpress and added some javascript and a contact form to it. In the code below the only relevant code is the form. and the javascript. The javascript has been tested and it works.
https://jsfiddle.net/607L7p3u/. Whenever i try it on a wordpress page it doesnt work. Instead the only thing that happens is the page gets refreshed and the url changes to something like /?product1=12&product1=13
The code is here:
<?php /*Template Name: CutomPageT1*/
global $post,
$mk_options;
$page_layout = get_post_meta( $post->ID, '_layout', true );
$padding = get_post_meta( $post->ID, '_padding', true );
if ( empty( $page_layout ) ) {
$page_layout = 'full';
}
$padding = ($padding == 'true') ? 'no-padding' : '';
get_header(); ?>
<div id="theme-page">
<div class="mk-main-wrapper-holder">
<div id="mk-page-id-<?php echo $post->ID; ?>" class="theme-page-wrapper mk-main-wrapper <?php echo $page_layout; ?>-layout <?php echo $padding; ?> mk-grid vc_row-fluid">
<div class="theme-content <?php echo $padding; ?>" itemprop="mainContentOfPage">
<?php if ( have_posts() ) while ( have_posts() ) : the_post();?>
<form>
<input type="checkbox" id="product1" name="product1" value="12">
<input type="checkbox" id="product2" name="product1" value="13">
<input type="checkbox" id="product3" name="product1" value="14">
<button type="submit">Subscribe</button>
</form>
<div class="clearboth"></div>
<?php wp_link_pages( 'before=<div id="mk-page-links">'.__( 'Pages:', 'mk_framework' ).'&after=</div>' ); ?>
<?php endwhile; ?>
</div>
<?php
if(isset($mk_options['pages_comments']) && $mk_options['pages_comments'] == 'true') {
comments_template( '', true );
}
?>
<?php if ( $page_layout != 'full' ) get_sidebar(); ?>
<div class="clearboth"></div>
</div>
<div class="clearboth"></div>
</div>
</div>
<script>
var form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const values = Array.from(document.querySelectorAll('input[type=checkbox]:checked'))
.map(item => item.value)
.join(',');
console.log('test.com/addtocart?${values}');
});
//test
console.log('Lekker spelen');
</script>
<?php get_footer(); ?>

I solved it by using linking a function to the form using "onsubmit"
<form onSubmit="return handleClick()">
<input type="checkbox" id="product1" name="product1" value="12">
<input type="checkbox" id="product2" name="product1" value="13">
<input type="checkbox" id="product3" name="product1" value="14">
<button type="submit">Subscribe</button>
</form>
And then wrapping my existing JS code in a javascript function:
function handleClick(){
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
});
const values = Array.from(document.querySelectorAll('input[type=checkbox]:checked'))
.map(item => item.value)
.join(',');
console.log('test.com/addtocart?'+values);
}

Related

How to modify a payment form in a wordpress plugin?

I'm trying to create a food delivery web page with the wordpress restropress plugin,
the page looks like this: https://restropress.magnigenie.com/demo/food-items/
And the problem I have is that in the checkout form I want to remove the city field
since being a delivery I obviously only make deliveries in my city
and I don't want my customers to go through that redundancy.
I would also like to change the postcode field from text to a drop-down.
I have tried with some action hooks setting as "unset" the field "city" but nothing.
In the html of the page I managed to make the changes directly
but when I updated the plug-in changes were lost.
Can you help me? This is the plugins code that I'm trying to modify:
<fieldset id="rpress_checkout_order_details">
<legend><?php echo apply_filters( 'rpress_checkout_order_details_text', esc_html__( 'Order Details', 'restropress' ) ); ?></legend>
<?php do_action( 'rpress_purchase_form_before_order_details' ); ?>
<?php
if( rpress_selected_service() == 'delivery' ) :
$customer = RPRESS()->session->get( 'customer' );
$customer = wp_parse_args( $customer, array( 'delivery_address' => array(
'address' => '',
'flat' => '',
'city' => '',
'postcode' => '',
) ) );
$customer['delivery_address'] = array_map( 'sanitize_text_field', $customer['delivery_address'] );
if( is_user_logged_in() ) {
$user_address = get_user_meta( get_current_user_id(), '_rpress_user_delivery_address', true );
foreach( $customer['delivery_address'] as $key => $field ) {
if ( empty( $field ) && ! empty( $user_address[ $key ] ) ) {
$customer['delivery_address'][ $key ] = $user_address[ $key ];
} else {
$customer['delivery_address'][ $key ] = '';
}
}
}
$customer['delivery_address'] = apply_filters( 'rpress_delivery_address', $customer['delivery_address'] );
?>
<p id="rpress-street-address" class="rp-col-md-6 rp-col-sm-12">
<label class="rpress-street-address" for="rpress-street-address">
<?php esc_html_e('Street Address', 'restropress') ?>
<span class="rpress-required-indicator">*</span>
</label>
<input class="rpress-input" type="text" name="rpress_street_address" id="rpress-street-address" placeholder="<?php esc_html_e('Street Address', 'restropress'); ?>" value="<?php echo $customer['delivery_address']['address']; ?>" />
</p>
<p id="rpress-apt-suite" class="rp-col-md-6 rp-col-sm-12">
<label class="rpress-apt-suite" for="rpress-apt-suite">
<?php esc_html_e('Apartment, suite, unit etc. (optional)', 'restropress'); ?>
</label>
<input class="rpress-input" type="text" name="rpress_apt_suite" id="rpress-apt-suite" placeholder="<?php esc_html_e('Apartment, suite, unit etc. (optional)', 'restropress'); ?>" value="<?php echo $customer['delivery_address']['flat']; ?>" />
</p>
<p id="rpress-city" class="rp-col-md-6 rp-col-sm-12">
<label class="rpress-city" for="rpress-city">
<?php _e('Town / City', 'restropress') ?>
<span class="rpress-required-indicator">*</span>
</label>
<input class="rpress-input" type="text" name="rpress_city" id="rpress-city" placeholder="<?php _e('Town / City', 'restropress') ?>" value="<?php echo $customer['delivery_address']['city']; ?>" />
</p>
<p id="rpress-postcode" class="rp-col-md-6 rp-col-sm-12">
<label class="rpress-postcode" for="rpress-postcode">
<?php _e('Postcode / ZIP', 'restropress') ?>
<span class="rpress-required-indicator">*</span>
</label>
<input class="rpress-input" type="text" name="rpress_postcode" id="rpress-postcode" placeholder="<?php _e('Postcode / ZIP', 'restropress') ?>" value="<?php echo $customer['delivery_address']['postcode']; ?>" />
</p>
<?php endif; ?>
<p id="rpress-order-note" class="rp-col-sm-12">
<label class="rpress-order-note" for="rpress-order-note"><?php echo sprintf( __('%s Instructions', 'restropress'), rpress_selected_service( 'label' ) ); ?></label>
<textarea name="rpress_order_note" class="rpress-input" rows="5" cols="8" placeholder="<?php echo sprintf( __('Add %s instructions (optional)', 'restropress'), strtolower( rpress_selected_service( 'label' ) ) ); ?>"></textarea>
</p>
<?php do_action( 'rpress_purchase_form_order_details' ); ?>
<?php do_action( 'rpress_purchase_form_order_details_fields' ); ?>
</fieldset>
I put this following hook in the functions.php file and it didn't work:
function wp_edit_checkout_fields($fields){
unset($fields['delivery_adress']['city']);
return $fields;
}
add_filter('rpress_purchase_form_order_details_fields', 'wp_edit_checkout_fields');
Note that, there is do_action( 'rpress_purchase_form_order_details_fields' ); in the plugin code. It is usually used with add_action, but not with add_filter.
Maybe you could take advantage of this filter call:
$customer['delivery_address'] = apply_filters( 'rpress_delivery_address', $customer['delivery_address'] );
Try something like this (put in your function.php file):
function your_custom_function($delivery_address) {
// Try to somehow process the city field here...
// First, you could output a variable
// to understand the data structure
print_r($delivery_address);
// and return the changed address
return $delivery_address;
}
add_filter( 'rpress_delivery_address', 'your_custom_function' );
Docs - https://developer.wordpress.org/reference/functions/add_filter/

How to delete values from JSON object array in php?

I have a PHP code and JSON as shown below:
PHP Code:
<?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
$output = array();
$output['en_desc']=$_POST['en_desc'];
$output['code']=$_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
}
?>
<?php if($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<input type="hidden" id="savechanges" name="savechanges" value="1">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else { echo 'Cannot read JSON settings file'; }?>
JSON:
{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}
The following DOM is generated through the PHP/JSON code above:
DOM (HTML):
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
<input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
<input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
The following JS code deletes a row from the DOM on click of a delete button. On refreshing the page,
the deleted row comes back again as everything is rendered through JSON.
JS code:
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
Problem Statement:
The above JS code is deleting the row (on click of a delete button) from the DOM but on refresing the page, everything is rendered again.
I am wondering what PHP code I need to add so that it delete the values from the JSON on saving the form when row is deleted from DOM through JS.
Step 1: User delete the row from the DOM on click of a delete button.
Step 2: On saving the form and rendering the page, that deleted row should not be present.
I know I have to use unset function in order to remove the values from the JSON but I am not sure how I can integrate it in the form.
unset($data->code);
unset($data->en_desc);
You have a typo here:
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
it should be
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
Look at the "s" :)
Edit: you also were saving the new file without actually checking if there is a post happening, here is the full code:
<?php
if (isset($_POST['submit'])) {
$output = array();
$output['en_desc'] = $_POST['en_desc'];
$output['code'] = $_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_committees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if (file_exists('../feeds/ptp-ess_landing_committees.json')) {
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
}
?>
<?php if ($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit" name="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else {
echo 'Cannot read JSON settings file';
} ?>
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>

Checkboxes: How can I check two sets at the same time?

I have 2 sets of checkboxes in my webpage, and I have a small script that is checking the boxes and not the others when I click one, which is what I want.
Unfortunately, it only checks one set of boxes, and leaves the other set unchecked.
Although on reloading my page both sets are checked, this is due to my post variable. I will show you the code.
Can anybody see where I could update it to check both boxes when clicking one box?
<div id='checkbox-container'>
<input type="checkbox" id="small" name="displaytypethumbs" value="minlist" <?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="small" class="smalllistings">Thumbs</label>
</input>
<input type="checkbox" id="large" name="displaytypegallery" value="maxlist" <?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="large" class="largelistings" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings" name="displaytypefull" value="fulllist" <?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?>onclick="chbx(this)">
<label for="fulllistings" class="fulllistings" >Full Listing</label>
</input>
</div>
<div id='checkbox-container2'>
<input type="checkbox" id="small2" name="displaytypethumbs" value="minlist" class="smalllistingsbox"
<?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="small2" class="smalllistingsmain" >Thumbs</label>
</input>
<input type="checkbox" id="large2" name="displaytypegallery" value="maxlist" class="largelistingsbox"
<?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="large2" class="largelistingsmain" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings2" name="displaytypefull" value="fulllist"
<?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="fulllistings2" class="fulllistingsmain" >Full Listings</label>
</input>
</div>
</form>
<script>
function chbx(obj) {
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('small').checked = false;
document.getElementById('large').checked = false;
document.getElementById('fulllistings').checked = false;
document.getElementById('small2').checked = false;
document.getElementById('large2').checked = false;
document.getElementById('fulllistings2').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
Thanks guys, i should of thought about it before posting really, i chose the simple method . Very wet, But still did the job... Thanks for your help guys.
<div id='checkbox-container'>
<input type="checkbox" id="small" name="displaytypethumbs" value="minlist" <?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check1();">
<label for="small" class="smalllistings">Thumbs</label>
</input>
<input type="checkbox" id="large" name="displaytypegallery" value="maxlist" <?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check2();">
<label for="large" class="largelistings" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings" name="displaytypefull" value="fulllist" <?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?>onclick="chbx(this); check3();">
<label for="fulllistings" class="fulllistings" >Full Listing</label>
</input>
</div>
<div id='checkbox-container'>
<input type="checkbox" id="small2" name="displaytypethumbs" value="minlist" class="smalllistingsbox"
<?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check4();">
<label for="small2" class="smalllistingsmain" >Thumbs</label>
</input>
<input type="checkbox" id="large2" name="displaytypegallery" value="maxlist" class="largelistingsbox"
<?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check5();">
<label for="large2" class="largelistingsmain" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings2" name="displaytypefull" value="fulllist"
<?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check6();">
<label for="fulllistings2" class="fulllistingsmain" >Full Listings</label>
</input>
</div>
</form>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('small').checked = false;
document.getElementById('large').checked = false;
document.getElementById('fulllistings').checked = false;
document.getElementById('small2').checked = false;
document.getElementById('large2').checked = false;
document.getElementById('fulllistings2').checked = false;
document.getElementById(that.id).checked = true;
}
}
function check1(){document.getElementById('small2').checked = true; }
function check2(){document.getElementById('large2').checked = true; }
function check3(){document.getElementById('fulllistings2').checked = true; }
function check4(){document.getElementById('small').checked = true; }
function check5(){document.getElementById('large').checked = true; }
function check6(){document.getElementById('fulllistings').checked = true; }
</script>
/

Codeigniter update form does not submit

Codeigniter offers you a tutorial to get to know it and how to use it. This tutorial teaches you to create elements in a table in a database, but doesn't teach you how to update this elements. I am trying to make an update query using the codeigniter libraries, but the form from de update view doesn't submit.
AT NEWS_MODEL:
public function update_news($slug)
{
$this->load->helper('url');
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
$this->db->where('slug', $slug);
$this->db->update('news', $data);
}
AT NEWS CONTROLLER:
public function update($slug)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
// The form was NOT posted
// So we load the view
$data['news_item'] = $this->news_model->get_news($slug);
$this->load->view('templates/header', $data);
$this->load->view('news/update', $data);
$this->load->view('templates/footer');
}
else
{
// The form was submitted
$data = array(
'title' => $this->input->post('title'), //-->post variable
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text')
);
$this->news_model->update_news($slug, $data);
$this->load->view('news/success');
}
}
AT UPDATE VIEW:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ;?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update news item" />
</form>
I've tested the code with "console.log()" and the problem seems to be that the form of the update view doesn't submit, but I cannot figure why, because the form is similar to the create form, which does work perfectly:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
your problem is :
you use === instead of == in this line:
if ($this->form_validation->run() === FALSE)

PHP Form Validation,how to make form invisible

I am performing a Form Validation in PHP. My purpose is to show the error message at the same page with form, in order to be clear for the user.
But I have to problems. First how to hide my form, where are no errors in submitting it(I want to print onl one message in this case and to hide the frm). I am trying to use:
if(false === $error)
{
//Validimi perfundoi me sukses!
echo "<script>
document.getElementById('wrap').style.display = 'none';
</script>";
echo $name;
}
but it does not function.
Second I am having problems with checkbox validation. I am using the array $activity, to save values from checkbox, as they may be multiple values, but when the user select no value at all at the checkbox part, it gives me the error that: Warning: in_array() expects parameter 2 to be array, null given even i have initialized $activity as an arra: $activity=array();.
<?php
$name_error='';
$device_error ='';
$OS_error='';
$activity_error='';
$device='';
$OS='';
$activity=array();
if(!empty($_POST['submitted']))
{//nese form eshte submitted atehere validohen fushat
$name = trim($_POST['name']);//heq hapesirat
$error = false;
if(empty($name))
{
$name_error='Emri eshte bosh. Ju lutem plotesoni emrin.';
$error=true;
}
if(empty($_POST['device']))
{
$device_error = "Ju lutem selektoni nje pajisje";
$error=true;
}
else
{
$device = $_POST['device'];
}
if(empty($_POST['OS']))
{
$OS_error ="Ju lutem selektoni sistemin operativ";
$error=true;
}
else
{
$OS = $_POST['OS'];
}
if(empty($_POST['activity']) || count($_POST['activity']) < 2)
{
$activity_error = "Ju lutem selektoni te pakten 2 aktivitete";
$error=true;
}
$activity = $_POST['activity'];
if(false === $error)
{
//Validimi perfundoi me sukses!
echo "<script>
document.getElementById('wrap').style.display = 'none';
</script>";
echo $name;
}
}
?>
<!DOCTYPE html>
<html >
<head>
<title>Computer Form</title>
<link href="compForm.css" rel="stylesheet" type="text/css" />
</head>
<body >
<div id="wrap" style="display: block">
<form method="post" action='?' id="compform" >
<div>
<div class="cont_order">
<fieldset>
<legend>Beni zgjedhjen tuaj!</legend>
<div class='field_container'>
<label >Zgjidhni pajisjen qe perdorni me shpesh:</label>
<span class="error"><?php echo $device_error;?></span>
<label class='radiolabel'><input type="radio" name="device" value="Desktop"
<?php echo ($device=='Desktop')? 'checked':''; ?>/>Desktop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Laptop"
<?php echo ($device=='Laptop')? 'checked':''; ?> />Laptop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Tablet"
<?php echo ($device=='Tablet')? 'checked':''; ?> />Tablet</label><br/>
</div>
<div class='field_container'>
<label for="OS">Zgjidhni Sistemin e Operimit qe perdorni:</label >
<span class='error'><?php echo $OS_error?></span>
<select id="OS" name='OS' >
<option value="">Zgjidhni OS</option>
<option <?php echo $OS=='Windows'?'selected':''; ?> >Windows</option>
<option <?php echo $OS=='Linux'?'selected':''; ?> >Linux</option>
<option <?php echo $OS=='Mac'?'selected':''; ?> >Mac</option>
</select>
</div>
<div class='field_container'>
<label >Selektoni dy aktivitetet qe preferoni me shume:</label>
<span class='error'><?php echo $activity_error ?></span>
<label><input type="checkbox" value="Programim Desktop" name='activity[]'
<?php echo (in_array('Programim Desktop',$activity)) ?'checked':'' ?> />Programim Desktop</label>
<label><input type="checkbox" value="Programim Web" name='activity[]'
<?php echo (in_array('Programim Web',$activity)) ?'checked':'' ?> />Programim Web</label>
<label><input type="checkbox" value="Dizenjim" name='activity[]'
<?php echo (in_array('Dizenjim',$activity)) ?'checked':'' ?> />Dizenjim</label>
<label><input type="checkbox" value="Analize te dhenash" name='activity[]'
<?php echo (in_array('Analize te dhenash',$activity)) ?'checked':'' ?> />Analize te dhenash</label>
<label><input type="checkbox" value="Kerkim shkencor" name='activity[]'
<?php echo (in_array('Kerkim shkencor',$activity))?> />Kerkim shkencor</label>
</div>
</fieldset>
</div>
<div class="cont_details">
<fieldset>
<legend>Detajet e kontaktit</legend>
<label for='name'>Emri</label>
<input type="text" id="name" name='name'
value='<?php echo htmlentities($name) ?>' />
<span class='error'><?php echo $name_error ?></span>
<br/>
<label for='address'>Adresa e emailit</label>
<input type="email" id="address" name='address' />
<br/>
</fieldset>
</div>
<input type='submit' name='submitted' id='submit' value='Submit' />
</div>
</form>
</div>
</body>
</html>
Here's my quick solution (untested). Let's clean up your code a little:
Instead of using (and wasting) separate variables for each error message, let's use an associative array called $errors. The keys will be the name of the inputs and the values will be their respective error messages.
To ensure that you don't get warnings from undeclared variables, we will declare variables for each input at the top of the page.
Let's also use a new variable $submitted to know whether the form was submitted or not.
Now, if the form was $submitted and there are no (!) $errors, then we hide the form. Otherwise, we show the form and any errors if there are any.
<?php
$name = '';
$device = '';
$OS = '';
$activity = array();
$submitted = !empty($_POST['submitted']);
$errors = array();
if ($submitted) {
//nese form eshte submitted atehere validohen fushat
if (empty($_POST['name'])) {
$errors['name'] ='Emri eshte bosh. Ju lutem plotesoni emrin.';
} else {
$name = trim($_POST['name']);
}
if (empty($_POST['device'])) {
$errors['device'] = "Ju lutem selektoni nje pajisje";
} else{
$device = $_POST['device'];
}
if (empty($_POST['OS'])) {
$errors['OS'] = "Ju lutem selektoni sistemin operativ";
} else {
$OS = $_POST['OS'];
}
if (empty($_POST['activity']) || count($_POST['activity']) < 2) {
$errors['activity'] = "Ju lutem selektoni te pakten 2 aktivitete";
} else {
$activity = $_POST['activity'];
}
}
?>
<!DOCTYPE html>
<html >
<head>
<title>Computer Form</title>
<link href="compForm.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php if ($submitted && !$errors) : ?>
<?php echo $name ?>
<?php else : ?>
<div id="wrap">
<form method="post" action='?' id="compform" >
<div>
<div class="cont_order">
<fieldset>
<legend>Beni zgjedhjen tuaj!</legend>
<div class='field_container'>
<label >Zgjidhni pajisjen qe perdorni me shpesh:</label>
<span class="error"><?php echo isset($errors['device']) ? $errors['device'] : '' ?></span>
<label class='radiolabel'><input type="radio" name="device" value="Desktop"
<?php echo $device == 'Desktop' ? 'checked' : '' ?>/>Desktop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Laptop"
<?php echo $device == 'Laptop' ? 'checked' : '' ?> />Laptop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Tablet"
<?php echo $device == 'Tablet' ? 'checked' : '' ?> />Tablet</label><br/>
</div>
<div class='field_container'>
<label for="OS">Zgjidhni Sistemin e Operimit qe perdorni:</label >
<span class='error'><?php echo isset($errors['OS']) ? $errors['OS'] : '' ?></span>
<select id="OS" name='OS' >
<option value="">Zgjidhni OS</option>
<option <?php echo $OS == 'Windows' ? 'selected' : '' ?> >Windows</option>
<option <?php echo $OS == 'Linux' ? 'selected' : '' ?> >Linux</option>
<option <?php echo $OS == 'Mac' ? 'selected' : '' ?> >Mac</option>
</select>
</div>
<div class='field_container'>
<label >Selektoni dy aktivitetet qe preferoni me shume:</label>
<span class='error'><?php echo isset($errors['activity']) ? $errors['activity'] : '' ?></span>
<label><input type="checkbox" value="Programim Desktop" name='activity[]'
<?php echo in_array('Programim Desktop', $activity) ? 'checked' : '' ?> />Programim Desktop</label>
<label><input type="checkbox" value="Programim Web" name='activity[]'
<?php echo in_array('Programim Web', $activity) ? 'checked' : '' ?> />Programim Web</label>
<label><input type="checkbox" value="Dizenjim" name='activity[]'
<?php echo in_array('Dizenjim', $activity) ? 'checked' : '' ?> />Dizenjim</label>
<label><input type="checkbox" value="Analize te dhenash" name='activity[]'
<?php echo in_array('Analize te dhenash', $activity) ? 'checked' : '' ?> />Analize te dhenash</label>
<label><input type="checkbox" value="Kerkim shkencor" name='activity[]'
<?php echo in_array('Kerkim shkencor', $activity) ? 'checked' : '' ?> />Kerkim shkencor</label>
</div>
</fieldset>
</div>
<div class="cont_details">
<fieldset>
<legend>Detajet e kontaktit</legend>
<label for='name'>Emri</label>
<input type="text" id="name" name='name' value='<?php echo htmlentities($name) ?>' />
<span class='error'><?php echo isset($errors['name']) ? $errors['name'] : '' ?></span>
<br/>
<label for='address'>Adresa e emailit</label>
<input type="email" id="address" name='address' />
<br/>
</fieldset>
</div>
<input type='submit' name='submitted' id='submit' value='Submit' />
</div>
</form>
</div>
<?php endif ?>
</body>
</html>
You can check the $_POST['submitted'] as below pseudocode:
//form is submitted
if isset $_POST['submitted']
//process form and show error message
else
//show form

Categories