jQuery getting previous input value - javascript

<div class="panel-footer">
<div class="input-group">
<input id="btn-input" type="text" class="form-control input-sm chat_input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="btn-chat">Wyślij</button>
</span>
</div>
</div>
I have HTML like above. My question is how to get the input value when I click on #btn-chat. I have been trying of jQuery functions like .prev() and .prevAll() but those didn't work for me.

Given that the input element has an id attribute it should be unique, so you can select it directly without the need to traverse the DOM:
$('#btn-chat').click(function() {
var inputVal = $('#btn-input').val();
// do something with the value here...
});
If, for whatever reason, you still want to use DOM traversal you can use closest() to get the nearest common parent to both elements, and then find():
$('#btn-chat').click(function() {
var inputVal = $(this).closest('.input-group').find('input').val();
// do something with the value here...
});
If you have multiple elements in your page with the same id attribute then your HTML is invalid and you would need to change it. In that case, use class attributes to identify and select the elements.

$("#btn-chat").click(function(){
var input_values = $(this).parent().parent().find("input").val();
alert(input_values);
});

As #RoryMcCrossan has pointed out, if you have multiple elements with the same id attribute, you would need to use a class attribute instead.
$(function() {
$('.btn-chat').on('click', function() {
var val = $(this).closest('.input-group').find('input.btn-input').val();
//OR $(this).parent().prev().val();
console.log( val );
});
});
$(function() {
$('.btn-chat').on('click', function() {
var val = $(this).closest('.input-group').find('input.btn-input').val();
console.log( val );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel-footer">
<div class="input-group">
<input type="text" class="form-control input-sm chat_input btn-input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm btn-chat">Wyślij</button>
</span>
</div>
</div>
<div class="panel-footer">
<div class="input-group">
<input type="text" class="form-control input-sm chat_input btn-input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm btn-chat">Wyślij</button>
</span>
</div>
</div>
<div class="panel-footer">
<div class="input-group">
<input type="text" class="form-control input-sm chat_input btn-input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm btn-chat">Wyślij</button>
</span>
</div>
</div>

Related

jQuery to hide and show textarea

I have a textarea that I want to show/hide when ever I click a button
and also I need it to target this way because ill be using it in an undefined number of times
SAMPLE IMAGE HERE
SAMPLE IMAGE HERE
here is the HTML that I want to
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2"><i class="bi bi-plus-circle"></i></button>
</div>
<textarea class="form-control" id="multipleNameReq"></textarea>
and here is the script I try to use hiding/Showing it
$('body').on('click', '.buttonMultipleNameReq',function(){
const element1 = $(this);
const target1 = element1.parent().parent().find("#multipleNameReq");
console.log(target1);
if (target1.style.display === "none") {
target1.style.display = "block";
} else {
target1.style.display = "none";
}
})
the accepted answer will work fine for nonduplicate id of textarea or any other elements, but as you have shown in your image if you want to work this for multiple textarea or any elements I suggest you use the class attribute instead of the id attribute, here is the explanation for why to not use same id multiple times,
Duplicate IDs are common validation errors that may break the accessibility of labels, e.g., form fields, and table header cells.
To fix the problem, change an ID value if it is used more than once to be sure each is unique.
here below is some piece of code that may help you to get what are you looking for
$('body').on('click', '.buttonMultipleNameReq',function(e){
let textArea = $(e.target).parent().parent().find('textarea');
if(textArea.css('display') == "block"){
textArea.hide()
}else{
textArea.show()
}
})
.multipleNameReq{
display:block
}
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Using toggle function
here below is simpler code using jquery toggle, here you can read about toggle
$('body').on('click', '.buttonMultipleNameReq',function(e){
$(e.target).parent().parent().find('textarea').toggle();
})
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Since you're using jQuery you could use it's syntax:
To get element:
$('#multipleNameReq');
To Check if element is visible and not hidden:
$('#multipleNameReq').is(":visible");
To Show:
$('#multipleNameReq').show();
To Hide:
$('#multipleNameReq').hide();
A solution to add into your click function would look like:
if ($('#multipleNameReq').is(":visible")) {
$('#multipleNameReq').hide();
} else {
$('#multipleNameReq').show();
}
To access and change the style of an element you need to use the css function.
$('body').on('click', '.buttonMultipleNameReq', function() {
const element1 = $(this);
const target1 = element1.parent().parent().find("#multipleNameReq");
if (target1.css('display') === "none") {
target1.css('display', "block");
} else {
target1.css('display', "none");
}
})
<div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">Click<i class="bi bi-plus-circle"></i></button>
</div>
<textarea class="form-control" id="multipleNameReq" style="display: block;"></textarea>
</div>

Javascript function to toggle 2 divs and change button text - tageting different ID

I have multiple groups of DIV´s with each their button, in these groups I have 2 DIVS that should toggle between them on click on that button, and also switch the content on the buttons, but each group and button have their own unique ID.
The button ID´s are defined with EditButton<%=DataCon("ID")%> (Which gives EditButton1, EditButton2, EditButton3 .. etc) and the 2 DIVS in each group is called EditData<%=DataCon("ID")%> and TextData<%=DataCon("ID")%> (I.e EditData1 and TextData)
The button serverside:
<button id="EditButton<%=DataCon("ID")%>" class="btn btn-success" data-text-swap="<< Luk Redigering">Åben Redigering >></button>
Which result in:
<button id="EditButton1" class="btn btn-success" data-text-swap="<< Luk Redigering">Åben Redigering >></button>
The Severside JavaScript (ASP) I have:
$(function(){
$('div.EditData<%=DataCon("ID")%>').hide();// hide it initially
$('button').on('click', function(){
$('div.EditData<%=DataCon("ID")%>, div.TextData<%=DataCon("ID")%>').toggle();
});
});
$("button.EditButton<%=DataCon("ID")%>").on("click", function() {
var el = $(this);
if (el.text() == el.data("text-swap")) {
el.text(el.data("text-original"));
} else {
el.data("text-original", el.text());
el.text(el.data("text-swap"));
}
});
Which results in :
$(function(){
$('div.EditData1').hide();// hide it initially
$('button').on('click', function(){
$('div.EditData1, div.TextData1').toggle();
});
});
$("button.EditButton1").on("click", function() {
var el = $(this);
if (el.text() == el.data("text-swap")) {
el.text(el.data("text-original"));
} else {
el.data("text-original", el.text());
el.text(el.data("text-swap"));
}
});
The Severside DIVS in HTML :
<div class="EditData<%=DataCon("ID")%>" style="display:none">
<div class="input-group">
<input type="text" class="form-control" placeholder="<%=DataCon("FullName")%>" aria-label="Recipient's username" aria-describedby="basic-addon2" style="width: 100px;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button"><i class="far fa-save"></i></button>
</div>
</div>
</div>
<div class="TextData<%=DataCon("ID")%>">
<%=DataCon("FullName")%>
</div>
Which results in:
<div class="EditData1" style="display:none">
<div class="input-group">
<input type="text" class="form-control" placeholder="Some Name" aria-label="Recipient's username" aria-describedby="basic-addon2" style="width: 100px;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button"><i class="far fa-save"></i></button>
</div>
</div>
</div>
<div class="TextData1">
Some Name
</div>
The above script is obviously not working because I am not calling the DIVS and Buttons correctly, but how do I fix this?
Best Regards
Stig :-)
I think #Rory McCrossan's idea to use closest() would work, the only issue is that if you have display none on the container with the button in it, then the button won't be visible to begin with.
You could adjust your markup a bit so that the Edit button and the form are both siblings of a common parent. That would allow you to use nextSibling() in vanilla JS, or next() in jQuery
$('.toggle').on('click', function(event) {
$(this).next('.EditData').toggleClass('invisible');
let text = $(this).parent().find('.TextData').toggleClass('invisible');
let newText = $(this).text() === 'Åben Redigering >>' ? '<< Luk Redigering' : 'Åben Redigering >>';
$(this).text(newText);
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="EditButton1" class="toggle btn btn-success" data-text-swap="<< Luk Redigering">Åben Redigering >></button>
<div class="EditData invisible">
<div class="input-group">
<input type="text" class="form-control" placeholder="Some Name" aria-label="Recipient's username" aria-describedby="basic-addon2" style="width: 100px;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button"><i class="far fa-save"></i></button>
</div>
</div>
</div>
<div class="TextData">
Some more info should appear here below
</div>
</div>
If you do it this way, you're relying on the structure of your template. You don't need to use a dynamic id to do a query each time as long as you put your button that triggers the toggle in the same position relative to one another with the same class names, this should work. Let me know if I misunderstood what you were trying to do there and I can edit my answer :)

Change enabled to disabled and disabled to enable the bootstrap with jquery

How do I change the input from disabled to enabled when clicks and returns from disabled to enabled when clicked
HTML
<div class="col-md-2">
<input type="text" class="form-control" id="tes" name="tes" />
</div>
<br>
<div class="col-md-3">
<button type="submit" id="submit1" class="glyphicon glyphicon-ok success btn btn-primary btn" value=""> </button>
</div>
JQUERY
$('#submit1').click(function() {
$('#tes').prop("disabled",true);
$(this).toggleClass('glyphicon glyphicon-ok').toggleClass('glyphicon glyphicon-remove btn-danger');
});
Use this Generalized function in your project to make things enabled / disabled.
(function($) {
$.fn.toggleDisabled = function(){
return this.each(function(){
this.disabled = !this.disabled;
});
};
})(jQuery);
$('#submit1').click(function() {
$('#tes').toggleDisabled();
$(this).toggleClass('glyphicon glyphicon-ok').toggleClass('glyphicon glyphicon-remove btn-danger');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-2">
<input type="text" class="form-control" id="tes" name="tes" />
</div>
<br>
<div class="col-md-3">
<button type="submit" id="submit1" class="glyphicon glyphicon-ok success btn btn-primary btn" >Button </button>
</div>
You can use this one.
$('#submit1').click(function() {
$('#tes').prop("disabled",!$('#tes').prop("disabled"));
$(this).toggleClass('glyphicon glyphicon-ok').toggleClass('glyphicon glyphicon-remove btn-danger');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-2">
<input type="text" class="form-control" id="tes" name="tes" />
</div>
<br>
<div class="col-md-3">
<button type="submit" id="submit1" class="glyphicon glyphicon-ok success btn btn-primary btn" value="Submit">SUbmit </button>
</div>
.prop(property) will return whether the property is set. You can use this to check the value and toggle it based on it's current value.
if( $('#tes').prop("disabled") )
$('#tes').prop("disabled",false);
else
$('#tes').prop("disabled",true);
You could reduce this to:
$('#tes').prop("disabled", !$('#tes').prop("disabled") )
This fetches the current value of the property, negates it with !, then sets that as the new value
If what you want is to toggle the disable prop:
$('#submit1').click(function() {
$('#tes').prop("disabled", !$('#tes').prop("disabled"));
});

Checkboxes weird behaviour in AngularJS ng-repeat

I've a form containing input fields and checkboxes (table crud generating dynamically). See the image below:
Here, In my clients modal dialog form I've implemented small crud for adding/updating/deleting Providers data and showing table below of it on the fly.
Following is my code:
View:
<form name="clientForm" ng-submit="check(id)" ng-controller="ClientsController">
<div class="form-group">
<label for="name">Name</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-hand-right"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Name" ng-model="client.name">
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Email" ng-model="client.email">
</div>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-earphone"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Phone" ng-model="client.phone">
</div>
</div>
<div class="form-group">
<label for="phone">Providers</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-hand-right"></i></span>
<input type="text" class="form-control" id="title" ng-model="provider.provider_name" placeholder="Enter Provider Name">
</div>
<br>
<button type="button" id="addbtn" class="btn btn-sm btn-primary" ng-click="addProvider()">Add Provider</button>
<button type="button" id="editbtn" class="btn btn-sm btn-info" ng-click="updateProvider(id)">Update Provider</button>
<button type="button" id="editbtn" class="btn btn-sm btn-default" ng-click="clearProvider()">Clear Provider</button>
<br>
<table style="width: 50%; margin-top: 10px;" class="">
<tbody>
<tr ng-repeat="val in providersData">
<td>
<input type="checkbox" name="providersData" ng-model="$parent.client.providersList" value="{{val._id}}"/>
</td>
<td>{{val.provider_name}}</td>
<td>
<a style="color: blue;" href="javascript:void(0);" ng-click="editProvider(val._id)"><i class="glyphicon glyphicon-edit"></i></a>
<a style="color: red;" href="javascript:void(0);" title="Delete" confirmed-click="removeProvider(val._id)" ng-confirm-click="Are you sure you want to remove provider?"><i class="glyphicon glyphicon-trash"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="well well-lg text-center bg-gray">
<button class="btn btn-success" ng-if="id">Save Client</button>
<button class="btn btn-danger" ng-if="id" title="Delete" confirmed-click="remove(client._id)" ng-confirm-click="Are you sure you want to remove?">Delete</button>
<button type="button" class="btn btn-warning" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button class="btn btn-success" ng-if="!id">Add Client</button>
</div>
</form>
Controller:
$scope.showModal = false;
$scope.client = {};
$scope.provider = null;
$scope.addClient = function () {
alert(JSON.stringify($scope.client));
$http.post('/clients', {param: $scope.client}).success(function (response) {
if (response) {
alert("Client added successfully");
$scope.client = "";
refresh();
$scope.closemodal();
}
});
};
Now I want to insert/update selected checkboxes value to db along with Name, Email, and Phone field.
Here I'm facing following issues:
Whenever I'm clicking on any checkbox its checking all checkboxes.
After clicking on Add Client button its showing result of alert(JSON.stringify($scope.client)) like this
{"name":"asdfdsafasdf","email":"sdf","phone":"sadf","providersList":{"id":true}}
In mongodb its showing like this:
I've search a lot tried this and ng-model="$parent.client.providersList.id" but still its not working.
I'm beginner in AngularJS and just started working on it.
Any help would be appreciated.
You should use ng-true-value & ng-false-value over the checkbox(I'm considering default value to be 0). And then use $index of providersData ng-repeat to create an array of client.providersList.
Markup
<input type="checkbox" name="{{'providersData'+$index}}"
ng-model="client.providersList[$index].id" ng-true-value="val._id" ng-false-value="0" />
You are facing this problem because of the value of your ng-model attribute. The value for ng-model attribute must be different for each checkbox. Here, try this:
<input type="checkbox" name="providersData" ng-model="client.providersList{{$index}}" ng-value="val._id" />
Try something like this:
$scope.client = {};
$scope.client.providersList = [];
// Now watch the model for changes
$scope.$watch('client', function(){
// When the checkbox is selected it returns true
if($scope.client.providersList1 == true){
$scope.client.providersList.push({"id": value})
}
// Repeat the if statements for all the checkboxes (or use a for loop)
}, true);

jQuery modify element children

My Bootstrap list has on each item a "add" button. After click on add, I modify the item and add it to another list-group.
But if I modify the button-element nothing happens. I dont know why, I tried out a lot of methods, but nothing works.
This is the default item:
<div class="list-group-item" data-id="399">
<div class="input-group input-group-sm">
<span class="input-group-addon" style="width:100%">Item-Name</span>
<div class="input-group-btn">
<button type="button" class="btn btn-success item-add">+</button>
</div>
</div>
</div>
This is what I want:
<div class="list-group-item" data-id="399">
<div class="input-group input-group-sm">
<span class="input-group-addon" style="width:100%">Item-Name</span>
<input class="form-control" placeholder=" Suchbegriffe" value="" style="min-width:150px;" type="text">
<div class="input-group-btn">
<button type="button" class="btn btn-success item-remove">x</button>
</div>
</div>
</div>
The ".item-add" jQ function:
var elem = $(this).parent().parent();
$(elem).children(':eq(last)').removeClass('btn-success').addClass('btn-danger');
$(elem).children(':eq(0)').after('<input type="text" class="form-control" placeholder=" Suchbegriffe" value="' + $('#parameters').val() + '" style="min-width:150px;">');
$(elem).children(':eq(0)').html($(elem).children(':eq(0)').html().substr(0, 15) + '...');
elem = $(elem).parent();
$('#item-list-search').append(elem);
If I use console.log($(elem).children(':eq(last)')); it display the <button> element, but nothing change.
It should be more like this:
$(elem).children(':eq('+last+')').removeClass('btn-success').addClass('btn-danger');
Instead of this:
$(elem).children(':eq(last)').removeClass('btn-success').addClass('btn-danger');
Because you have to concatinate it, to make it look like a string. Since last is javasccript. So now it the button will actually change.
I did a JsFiddle for you, see here https://jsfiddle.net/tnya6b1e/
With this js :
$('.item-add').click(function() {
if (!($('#newitem').length > 0)) {
$('.item-add').parents('.input-group-btn').prepend('<input id="newitem" type="text" class="form-control" placeholder=" Suchbegriffe" value="' + $('#parameters').val() + '" style="min-width:150px;">');
$(this).removeClass('btn-success').addClass('btn-danger');
}
});
$(elem).children(':eq('+last+')').removeClass('btn-success').addClass('btn-danger');
last is the JavaScript variable.So,it should be concate it with string

Categories