getting a div id using javascript in a foreach loop - javascript

I am using laravel and want to make an ajax call to retrieve the id of the product but as u can see here it will get only the first product id because they will have the same id (or the first when the page load)
but i want it to : when i press add to cart, the clicked product id is sent
and my skills are not that good , this is my first app, can any one help ?
here is the code
#foreach($row as $product)
<form method="post" id="reg-form">
<input type="hidden" name="post_id" id="post_id" value="{{ $product->slug }}">
{!! csrf_field() !!}
<div class="col-sm-10 col-lg-3 col-md-10 ">
<div class='productbox '>
#if($image = $product->images()->first())
<img src="{{ $image->thumbnail }} " class="img-responsive" alt="a" />
#endif
<div class="producttitle">{{ $product->name }}</div>
<div class="pull-right">
#for ($i = 5 - $product->rating ; $i < 5 ; $i++)
<a> <i class="price-text-color fa fa-star"></i></a>
#endfor
#for ($i = $product->rating ; $i < 5 ; $i++)
<a> <i class=" fa fa-star"></i></a>
#endfor
</div><br />
<p class="text-justify"></p>
<address class="ellipsis">
<strong>{{ $product->description }}</strong><br>
</address>
<address>
{{ $product->name }}<br>
</address>
<div class="productprice">
<div class="pull-right">
<input type="button" id="getre" class="btn btn-danger btm-sm " role="button" value="Add to Wishlist">
</div>
<div class="pricetext">
<input type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" value="Add to cart">
More Details <span class="glyphicon glyphicon-zoom-in"></span>
<!-- Edit <span class="glyphicon glyphicon-cog"></span> -->
</div>
</div>
</div>
</div>
</form>
#endforeach
this is the javascript
$(document).ready(function()
{
$(document).on('submit', '#reg-form', function()
{
var data = $("#post_id").val();
$.ajax({
type : 'POST',
url : '{{url("/ajax")}}',
data: {'name':data, '_token': $('input[name=_token]').val()},
success : function(data)
{
$(getRequest).replaceWith('<img id=getRequest width=50 height=40 src= http://www.cuisson.co.uk/templates/cuisson/supersize/slideshow/img/progress.BAK-FOURTH.gif> ');
setTimeout(function() {
$(getRequest).replaceWith(' <input type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" value="Add to cart"> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
}
});
return false;
});
});

You are trying to get an element with id="post_id". There could be a lot of these elements in your page. You need to get the element with id="post_id" that is inside your current form element. You can do it in this way:
var data = $(this).find("#post_id").val();

The model of your product should have a unique ID. So when you iterate over all your products, you should set the id of the div with the same ID of the model. Then you can get it with jquery by $(".your-product-div").attr("id")

Related

Pass value for asp-rout-data using jQuery code

I want to pass value of input tag with class "count"; I want to pass the value to asp-rout-count property in the a tag using jQuery or js. I have tried to do that with this code but I could not.
html markup:
<div class="qty col-4" style="float:left">
<h5>العدد </h5>
<span class="plus bg-info">+</span>
<input type="number" class="count" value="1" max="10">
<span class="minus bg-info">-</span><br /><br />
#if (Model.BuyingPrice <= currentUser.Balance)
{
<a asp-action="Buy" asp-route-id="#Model.Id" asp-route-count="r_id" class="btn btn-outline-info col-12">إشتري الان</a>
}
#if (Model.BuyingPrice > currentUser.Balance)
{
<a class="btn btn-outline-info col-12" href="#" onClick="alert('رصيدك الحالي غير كافي')">إشتري الان</a>
}
</div>
and jQuery part:
<script>
var r_id = getIdFromURL();
function getIdFromURL() {
var id = $(".count").val();
return id;
</script>

Pass javascript variable to appended row in Dynamic form

I am working with dynamic form.
I want to pass javascript value to append row. Here how can I pass uid value to appended row. I tried <?php echo $uid = "<script>document.write(uid)</script>"; ?> in append row.
Bbut it is not working.
Here is my code
default row
<div class="form-group row">
<?php $uid = '1';?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="<?php echo $uid;?>">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-info btn-sm" id="btnAddMoreSpecification" data-original-title="Add More">
<i class="fa fa-plus"></i>
</a>
</div>
</div>
<div id="divSpecificatiion">
</div>
Append row
<script type="text/template" id="temSpecification">
<div class="form-group row" style="padding-top:10px;">
<?php $uid =''; ?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="<?php echo $uid;?>">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-danger btn-sm btnRemoveMoreSpecification" data-original-title="Add More">
<i class="fa fa-times"></i>
</a>
</div>
</div>
</script>
$(document).ready(function (event) {
uid=1;uvd=2;$('#btnAddMoreSpecification').click(function ()
{$('#divSpecificatiion').append($('#temSpecification').html());uid++;uvd++; });
$(document).on('click', '.btnRemoveMoreSpecification', function () {
$(this).parent('div').parent('div').remove();
});
});
Output should be like this
Use something like this:
$(document).ready(function(event) {
uid = 1;
uvd = 2;
$('#btnAddMoreSpecification').click(function() {
uid++;
var templateHtml = $('#temSpecification').html();//save the html in a variable
var temp = $(templateHtml).find('input[type="text"]').val(uid).end();//find the input and append the new uid
$('#divSpecificatiion').append(temp);//append the new html to the div
});
$(document).on('click', '.btnRemoveMoreSpecification', function() {
$(this).parent('div').parent('div').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<?php $uid = '1';?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="<?php echo $uid;?>">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-info btn-sm" id="btnAddMoreSpecification" data-original-title="Add More">Add more
<i class="fa fa-plus"></i>
</a>
</div>
</div>
<div id="divSpecificatiion">
</div>
<script type="text/template" id="temSpecification">
<div class="form-group row" style="padding-top:10px;">
<?php $uid =''; ?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-danger btn-sm btnRemoveMoreSpecification" data-original-title="Add More">
<i class="fa fa-times"></i>
</a>
</div>
</div>
</script>

UPDATE Collection of data with array of inputs

I have 3 inputs in my form. residence[], mobile[], office[]. I also have buttons for each inputs that will append them when clicked. So far, I managed to insert 3 values for each input into my database. But how can I Update all of them ? This is my controller for update
public function postEdit(ReservedEditRequest $reserved_edit_request, $id) {
foreach (Input::get('residence','mobile','office') as $key => $val) {
$student_contacts = StudentContacts::where('student_contacts.student_id',$id)
->update([
'residence' => Input::get("residence.$key"),
'mobile' => Input::get("mobile.$key"),
'office' => Input::get("office.$key"),
]);
}
return redirect('registrar/register_student')->withErrors('mobile')->with('message', 'Student Details Successfully Modified');
}
the code above will retrieve a collection
residence----------------------mobile-----------------------office
VAL1----------------------------VAL1------------------------VAL1
VAL2----------------------------VAL2------------------------VAL2
VAL3----------------------------VAL3------------------------VAL3
and when i submit the form, it saves the 3rd VALUE for all fields making it
residence----------------------mobile-----------------------office
VAL3----------------------------VAL3------------------------VAL3
VAL3----------------------------VAL3------------------------VAL3
VAL3----------------------------VAL3------------------------VAL3
Any answer will be appreciated :) Thanks
EDITED
this is the form
<div class="col-xs-1">
<button type="button" id="add_field_button_residence" class="btn btn-sm btn-primary" pull-right>
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<div class="col-sm-3">
<div class="input_fields_wrap_residence">
#if($action == 1)
#foreach($student_contacts as $contacts)
<input type="text" name="residence[]" id="residence[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Residence e.g. (32)1234567" value="{{{$contacts -> residence}}}"/>
<span class="help-block">{!!$errors->first('residence', '<span class="help-block">:message </span>')!!}</span>
#endforeach
#else
<input type="text" name="residence[]" id="residence[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Residence e.g. (32)1234567" value="{{{Input::old('residence', isset($student_contacts) ? $student_contacts_residence : null )}}}"/>
<span class="help-block">{!!$errors->first('residence', '<span class="help-block">:message </span>')!!}</span>
#endif
</div>
</div>
<div class="col-xs-1">
<button type="button" id="add_field_button_mobile" class="btn btn-sm btn-primary" pull-right>
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<div class="col-sm-3">
<div class="input_fields_wrap_mobile">
#if($action == 1)
#foreach($student_contacts as $contacts)
<input type="text" name="mobile[]" id="mobile[]" class="form-control" pattern="(09)[0-9]{9}" placeholder="Mobile Phone" value="{{{$contacts -> mobile}}}" required/>
<span class="help-block">{!!$errors->first('mobile', '<span class="help-block">:message </span>')!!}</span>
#endforeach
#else
<input type="text" name="mobile[]" id="mobile[]" class="form-control" pattern="(09)[0-9]{9}" placeholder="Mobile Phone" value="{{{Input::old('mobile', isset($student_contacts) ? $student_contacts_mobile : null)}}}" required/>
<span class="help-block">{!!$errors->first('mobile', '<span class="help-block">:message </span>')!!}</span>
#endif
</div>
</div>
<div class="col-xs-1">
<button type="button" id="add_field_button_office" class="btn btn-sm btn-primary" pull-right>
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<div class="col-sm-3">
<div class="input_fields_wrap_office">
#if($action == 1)
#foreach($student_contacts as $contacts)
<input type="text" name="office[]" id="office[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Office e.g. (32)1234567" value="{{{$contacts->office}}}"/>
<span class="help-block">{!!$errors->first('office', '<span class="help-block">:message </span>')!!}</span>
#endforeach
#else
<input type="text" name="office[]" id="office[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Office e.g. (32)1234567" value="{{{Input::old('office', isset($student_contacts) ? $student_contacts_office : null )}}}"/>
<span class="help-block">{!!$errors->first('office', '<span class="help-block">:message </span>')!!}</span>
#endif
</div>
</div>
the button will append the inputs through javascript . Here is the code
$(document).ready(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap_mobile"); //Fields wrapper
var add_button = $("#add_field_button_mobile"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mobile[]" id="mobile[]" class="form-control" pattern="(09)[0-9]{9}" placeholder="Mobile Phone" value="{{{Input::old('mobile', isset($student_contacts) ? $student_contacts_mobile : null)}}}" required/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field_mobile", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
same code is applied to others

I want to call controller using javascript

Here, I am using codeigniter. I want to call controller method using javascript where view is called. I want to call view method after one second. I want to call popup from my dashboard, so I called it using controller. Dashboard is my "user_view.php" . From view of "user_home.php", I want to call "break_alert.php".
Here is my code:
Controller:
function alert_breaktime()
{
$this->load->view('break_alert');
}
View:
user_view.php:
<script type="text/javascript">
var timer = setTimeout(function()
{
alert('adsfadf');
window.location.href = "<?php echo site_url('welcome/alert_breaktime');?>
},1000);
</script>
break_alert.php:
<script src="<?=base_url()?>resource/js/jquery-2.1.1.min.js"></script>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Add Activity</h4>
</div>
<?php $attributes = array('class' => 'bs-example form-horizontal'); echo form_open(base_url().'activity/add',$attributes); ?>
<div class="modal-body">
<div class="form-group">
<label class="col-lg-2 control-label">Subject<span class="text-danger">*</span></label>
<div class="col-lg-10">
<input type="text" class="form-control holiday_name" name="holiday_name" required>
</div>
</div>
<div class="form-group row">
<button type="submit" class="btn btn-default col-md-2"><i class="fa fa-phone"></i> Call</button>
<button type="submit" class="btn btn-default col-md-2"><i class="fa fa-group"></i> Meeting</button>
<button type="submit" class="btn btn-default col-md-2"><i class="fa fa-tasks"></i> Task</button>
<button type="submit" class="btn btn-default col-md-2"><i class="fa fa-flag"></i> Deadline</button>
<button type="submit" class="btn btn-default col-md-2"><i class="fa fa-envelope"></i> Email</button>
<button type="submit" class="btn btn-default col-md-2"><i class="fa fa-cutlery"></i> Lunch</button>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Date<span class="text-danger">*</span></label>
<div class="input-group date col-lg-10" id="datetimepicker5">
<input ng-model="dt" type='text' class="col-sm-3 form-control" value="" readonly data-date-format="YYYY/MM/DD"/>
<span class="input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<textarea class="textarea" id="description"></textarea>
</div>
<div class="modal-footer">
<?=lang('close')?>
<button type="submit" class="btn btn-primary">Add Activity</button>
</div>
</div>
</div>
</div>
in your code the whole page is refresh after every second.
in place of "window.location.href" use ajax call and evaluate script code like this.
$.ajax({
url: "your url",
success: function(data){
$(data).find("script").each(function() {
eval($(this).text());
}
}
});
function alert_breaktime()
{
echo $this->load->view('break_alert');
}
After all, I got the solution and it works fine. So, here I am putting as a solution.
<script type="text/javascript">
$(document).ready(function() {
var $timer = 0;
function testbreak(){
if ($timer === 0) {
$("#bb").click();
$timer = 1;
}
}
setInterval(testbreak, 3000);
});
</script>
<div id='abc' style="display: none;">
<i class="fa fa-plus"></i> Add Activity
</div>

Append a entire div with all its elements using jquery

Using jQuery I want to append a entire div when a click event happens. I tried but it's not working.
When a user clicks the Add another image I want to append the entire div tag with all its elements.
Here is my code:
<form method="post" id="form_property" enctype="multipart/form-data">
<div class="row">
<div class="span4" id="image">
<h3><strong>4.</strong> <span>Add Images to your Property</span></h3>
<div class="fileupload fileupload-new control-group" data-provides="fileupload">
<label class="control-label" for="inputPropertyPrice">Image files</label>
<div class="input-append">
<div class="uneditable-input"> <i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div> <span class="btn btn-file">
<span class="fileupload-new">Select file</span>
<span class="fileupload-exists">Change</span>
<input type="file" name="files1" accept="image/*" />
</span>
</div>
</div>
</div>
<!-- /.span4 -->
</div>
<!-- /.row -->
<br/> <a id="another_image" class="btn btn-primary btn-small list-your-property" href="#">Add Another Image</a>
<br/>
<br/>
<input type="submit" name="submit" value=" Save images " class="btn btn-primary btn-large" style="float: left; width: 370px; height: 50px; margin-top: 10px">
</form>
Jquery
<script type="text/javascript">
$(document).ready(function(){
var count = 2;
$('#another_image').click (function(){
if(count < 7){
$('<br/><br/>
<div class="input-append">
<div class="uneditable-input">
<i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-file">
<span class="fileupload-new">Select file</span>
<span class="fileupload-exists">Change</span>
<input type="file" name="files'+ count +'" accept="image/*" />
</span>
</div>
').appendTo ("#image");
count++;
}
});
});
</script>
Can someone please help me to fix this?
Use .appendTo() along with clone().
If you don't use clone() the same div will get replaced and nothing will be updated in the target. You don't need to type/copy the whole html.
Syntax : $(Element_Selector).appendTo(TargetSelector).
$($('.input-append').first().clone()).appendTo("#image");
Fiddle
*Note: Cloning existing html might create duplicate Ids. Take care of it.
I prefer #Shaunak's answer which is more efficient, but if you want to follow in your way then check THIS DEMO and the below code
$(document).ready(function(){
var count = 2;
$('#another_image').click (function(){
if(count < 7){
$('<br/><br/>' +
'<div class="input-append">' +
'<div class="uneditable-input">'+
'<i class="icon-file fileupload-exists"></i>' +
'<span class="fileupload-preview"></span>' +
'</div><span class="btn btn-file">'+
'<span class="fileupload-new">Select file</span>'+
'<span class="fileupload-exists">Change</span>' +
'<input type="file" name="files'+ count +'" accept="image/*" />'+
'</span></div>').appendTo ("#image");
count++;
}
});
});

Categories

Resources