Jump to content

Adding a new group of fields onclick, not just one field


jasonc310771

Recommended Posts

I am wanting to have my page add a new row of fields not just the one as in this script.  So when submitted I can save each group of fields in to the DB.  The save to DB I hope will be simple.  But its getting the new row of fields added to the form that I am not able to do.

		<form id="form" method="POST" action="save_data.php">
			<input type="text" name="text_field[]">
			<button type="submit">SUBMIT</button>
		</form>
		<button onclick="add_field()">ADD FIELD</button>
		<script>
			function add_field(){
			    
				var x = document.getElementById("form");

	            // create an input field to insert
				var new_field = document.createElement("input");

				// set input field data type to text
				new_field.setAttribute("type", "text");

				// set input field name 
				new_field.setAttribute("name", "text_field[]");

                // select last position to insert element before it
				var pos = x.childElementCount;
				
				// insert element
				x.insertBefore(new_field, x.childNodes[pos]);
			}
		</script>

 

 

 

Link to comment
Share on other sites

Digging around a little more, I found this...

The first group datepickers work correctly, but adding new groups the datepicker does not work.

How do I get the datepickers to work no matter how many groups I add ?

<script>
		$(function() {
			<!--$.datepicker.setDefaults($.datepicker.regional['fi']);-->
			$( "#from" ).datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1,
			onClose: function( selectedDate ) {
			$( "#to" ).datepicker( "option", "minDate", selectedDate );
			}
            });
            $( "#to" ).datepicker({
            defaultDate: "+1w",
            regional: "fi",
            changeMonth: true,
            numberOfMonths: 1,
            onClose: function( selectedDate ) {
			$( "#from" ).datepicker( "option", "maxDate", selectedDate );
			}
			});
		});


  		$(document).ready(function(){
			$(".addMore").click(function(){		var fieldHTML = '<div class="eventGroup">'+$(".eventGroupCopy").html()+'</div>';	$('body').find('.eventGroup:last').after(fieldHTML);	});//add more fields group
			$("body").on("click",".remove",function(){	$(this).parents(".eventGroup").remove();	});//remove fields group
		});
</script>

			<form method="post" action="edit.php">
			<?php
	//			if ($getEventDetails->num_rows == 0) {
	//				while($eventDetail = $getEventDetails->fetch_assoc()) {
					?>
					<div class="eventGroup">
						<input type="text" name="eventName[]" placeholder="Enter name" value="<?php //if($_POST[) {  } else {  } ?>"><br>
						<input type="text" name="price[]" placeholder="Enter Price"><br>
						<input type="text" id="from" name="eventStart[]" placeholder="Enter Start Date"><br>
						<input type="text" id="to" name="eventEnd[]" placeholder="Enter End Date"><br>
						<a href="javascript:void(0)" class="remove">Remove</a>
					</div>
					<?php
	//				}
	//			}
			?>
			<div class="eventGroup" style="display: none;"></div>
			<a href="javascript:void(0)" class="addMore">Add more</a>
			<input type="submit" name="submit" value="SUBMIT"/>
			</form>
			<!-- copy of input fields group -->
			<div class="eventGroupCopy" style="display: none;">
				<input type="text" name="eventName[]" placeholder="Enter Event Name"><br>
				<input type="text" name="price[]" placeholder="Enter Price"><br>
						<input type="text" id="from" name="eventStart[]" placeholder="Enter Start Date"><br>
						<input type="text" id="to" name="eventEnd[]" placeholder="Enter End Date"><br>
				<a href="javascript:void(0)" class="remove">Remove</a><br><br>
			</div>

 

Link to comment
Share on other sites

1. IDs are unique. You cannot have more than one #from or #to on your page. Find some other means of identifying which inputs you want datepickers on.
2a. If you create a bunch of elements and some of them need to be hooked up with some Javascript stuff, (and you can't apply the Javascript stuff globally,) then hook up those new elements with the Javascript.
2b. When applying the datepicker, all you need is some jQuery collection - you can do whatever it takes to get a collection of the elements you want.
2c. There are multiple easy ways to have jQuery return you a set of elements somewhere specific and not across the entire document.

Link to comment
Share on other sites

31 minutes ago, Barand said:

Does it have to be a datepicker widget, or would an ordinary <input type='date'> be sufficient?

I did try this method to start with but what ever the reason was it did not work well (lack of understanding maybe)

Using datepicker work brilliantly for this so far, I just stumbled on an issue when I have the date picker in more than one group.

Link to comment
Share on other sites

After reading yet more documentation...  I now have this...

But the added groups datepicker does not show the calendar.

If I understand it correctly, I need to reinitialise the datepicker of the new group, but using the initPicker() does not seem to work. Even though it is initionising the others.

			<script>
             function initPicker() {
		$(function() {
			$( ".datepicker" ).datepicker({
				defaultDate: "+1w",
				changeMonth: true,
				numberOfMonths: 1,
				onClose: function( selectedDate ) {
				//$( ".datepicker" ).datepicker( "option", "minDate", selectedDate );
				}
			});
		});
}
initPicker(); 
              
              
              $(document).ready(function(){
				$(".addMore").click(function(){		var fieldHTML = '<div class="eventGroup">'+$(".eventGroupCopy").html()+'</div>';	$('body').find('.eventGroup:last').after(fieldHTML);	initPicker();alert("1");	});//add more fields group
				$("body").on("click",".remove",function(){	$(this).parents(".eventGroup").remove();	});//remove fields group
			});
			</script>
			<form method="post" action="editSpecialDatePrices.php">
			<?php
				if ($getEventDetails->num_rows != 0) {
					while($eventDetail = $getEventDetails->fetch_assoc()) {
					?>
					<div class="eventGroup">
						<input type="text" name="eventName[]" placeholder="Enter name" value="<?php echo($eventDetail['eventName']); ?>"><br>
						<input type="text" name="price[]" placeholder="Enter Price" value="<?php echo($eventDetail['pricePerNight']); ?>"><br>
						<input class="datepicker" type="text" name="eventStart[]" placeholder="<?php echo(date('d F Y', time())); ?>" value="<?php echo(date("d F Y", strtotime($eventDetail['eventStart']))); ?>"><br>
						<input class="datepicker" type="text" name="eventEnd[]" placeholder="<?php echo(date('d F Y', strtotime('+7 days'))); ?>" value="<?php echo(date("d F Y", strtotime($eventDetail['eventEnd']))); ?>"><br>
						<a href="javascript:void(0)" class="remove">Remove</a>
					</div>
					<?php
					}
				}
			?>
			<div class="eventGroup" style="display: none;"></div>
			<a href="javascript:void(0)" class="addMore">Add more</a>
			<input type="submit" name="submit" value="SUBMIT"/>
			</form>
			<!-- copy of input fields group -->
			<div class="eventGroupCopy" style="display: none;">
				<input type="text" name="eventName[]" placeholder="Enter Event Name"><br>
				<input type="text" name="price[]" placeholder="Enter Price"><br>
				<input class="datepicker" type="text" name="eventStart[]" placeholder="<?php echo(date('d F Y', time())); ?>" value=""><br>
				<input class="datepicker" type="text" name="eventEnd[]" placeholder="<?php echo(date('d F Y', strtotime('+7 days'))); ?>" value=""><br>
				<a href="javascript:void(0)" class="remove">Remove</a><br><br>
			</div>

 

Edited by jasonc310771
Link to comment
Share on other sites

6 hours ago, Barand said:

Does it have to be a datepicker widget, or would an ordinary <input type='date'> be sufficient?

So after some hours playing around with different code found here and there...  I have opted to create a test page using the basic type=date

All ok so far, but then I remembered why I went with datepicker...  The format shown in the field.  I really need it to show the full month name, as both UK and US visitors may use the site and this will cause the site to break if a US visitor uses 12-25-2023 !  so if someone uses 11-12-23, is it 12 November 2023 or 11 December 2023 !

How do I change the format of the input type to 'd F Y' ?

Yes I know the type=date shows the format required and you can not on my PC change the date manually, but what if this feature does not show correctly on their device, then they are left to enter manually.

Edited by jasonc310771
Link to comment
Share on other sites

I don't see the date format as a problem. A date type input field will use the client computer's date/time settings.

So, whereas you and I will see 11/08/2023 displayed today, Requinix and the rest of his contrary compatriots will see it as 08/11/2023 if they display your form.

In either case it will be sent in the form's data as 2023-08-11 to your PHP script. Make sure you use Y-m-d format for setting min, max and initial values.

In addition, the drop-down calendar removes any ambiguity

image.png.31abb4f95094f931c66a3705938ec404.png

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.