jquery regex out 0 from cloned element and insert it? - javascript

I'd like to learn how to regex out 0 from all elements inside clone and replace it with var count_rows.
//Duplicate table tr for multiple subtitle entry
$("#add_subtitle").on("click", function(){
var count_rows = $(".subs_row").length;
$("#sub_0").clone().insertBefore("#append_sub");
return false;
});
markup:
<tr valign="top" id="sub_0" data-num="0" class="subs_row">
<th scope="row"><label for="subtitle">Subtitle_0</label></th>
<td>
<input name="subtitle[0][url]" type="text" value="<?php echo $wovies_extra_data[0]['subtitle'][0]['url']; ?>" style="width:280px;">
<p class="howto">Url</p>
</td>
<td>
<input name="subtitle[0][lang]" type="text" value="<?php echo $wovies_extra_data[0]['subtitle'][0]['lang']; ?>" style="width:100px;">
<p class="howto">Language: Label</p>
</td>
<td>
<input name="subtitle[0][lang_code]" type="text" value="<?php echo $wovies_extra_data[0]['subtitle'][0]['lang_code']; ?>" style="width:50px;">
<p class="howto">Language: Code</p>
</td>
<td>
<input name="subtitle_def" type="radio" value="<?php echo $key; ?>" <?php if ($wovies_extra_data[0]['subtitle_def'] == $key) {echo "checked";} ?> style="width:100px;">
<p class="howto">Default?</p>
</td>
</tr>
oh and how can I make my regex not touch zero in width:50px; ?

Regexp is probably the wrong way to go here.
I would suggest to use a template system like http://mustache.github.io/ or underscore
If you really want to replace the zeros inside your existing HTML code you could target only certain attributes:
function replaceZero(row) {
return function (i, value) {
return value.toString().replace(0, row);
}
}
var $row = $("#sub_0");
$("label", $row).text(replaceZero(200));
$("input", $row).attr("name", replaceZero(200));
$row.attr("id", replaceZero(200));
Fiddle (simplified)
Fiddle (with clone)

Related

could not get input field value in jquery

I am creating an input field using foreach loop like this
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
$data is Array
(
[0] => Array
(
[asset_id] => abc-02
[asset_name] => Freezer
)
[1] => Array
(
[asset_id] => xyz-01
[asset_name] => Refrigerator
)
[2] => Array
(
[asset_id] => 300001
[asset_name] => Generator
)
)
and in javascript, I am trying to get the value using this code but it always alerts first value of the input.
<script type="text/javascript">
$(document).ready(function () {
var typename = $('#typename').val();
alert(typename);
});
</script>
i have to disable this input field when value is 'Generator'
Try:
$('[readonly].form-control').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td>
.val() called once will always produce only one value; .val() docs:
Get the current value of the first element in the set of matched elements .
HTML id attribute is supposed to be unique, try this instead.
<?php
$count = 0;
foreach($data as $key=>$val) {
?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:
$('[id^="typename_"]').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
</td>
Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.
You should never use same id for several elements.
Update you code for debug, and you'll see that you have an array:
<script type="text/javascript">
$(document).ready(function () {
var typename = $('[name="model[]"]')
.toArray().map(e => e.value);
alert(JSON.stringify(typename));
});
</script>
You should update your php, to set different id for each element drawn in a cycle, i.e:
<?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>
So you'll be able to address eash input separately:
var typename = $('#typename_1').val();
Use class instead of duplicate id like this.
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery loop your class and get value using this instant..
$(document).ready(function () {
$( ".clsValue" ).each(function( index ) {
var typename = $(this).val();
alert(typename);
});
});
try this ,
this will call alert function for each input with form-control class
$(document).ready(function () {
$(".form-control").each(function(){
alert($(this).val());
})
});
Set class="typename" instead of id="typename":
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
You can get values like this:
<script type="text/javascript">
$(document).ready(function () {
var typename1 = $('.typename')[0].val();
var typename2 = $('.typename')[1].val();
alert(typename1);
});
</script>
there is a big mistake in your code, you can't use same id for multiple input fields, when the loop run multiple input fields will create with same id, you have to make the id dynamic, you can make the id dynamic by appending some unique value to the id each time you create an input field the use that id to fetch the data.
Please let me know if you need sample code.
pure js approach;
replace id with class;
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
js
window.onload = alertTypeNames();
function alertTypeNames() {
document.getElementsByClassName('typename').map((inputTag) => {
alert(inputTag.value);
return true;
});
}
you fired with your id that's why it's fired only first element value.
this is how you can do that with your current code
$(document).ready(function () {
$('input[name="model[]"]').each(function(){
alert($(this).val());
});
});
However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.
The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.
<script type="text/javascript">
$(document).ready(function () {
$('.common-class').each(function() {
alert($(this).val());
});
});
</script>
<?php $incr_var = 1; ?>
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
Element id should be unique. And try it inside on event because dynamically adding elements will not grab ready state.
http://api.jquery.com/live/
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1 status">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery
$(document).on('change','.status',function(){
var $status = $(this).val();
if($status == 'not_working'){
$(this).closest('tr').find('.reason').removeAttr('disabled');
}
});
reason is class you have to give which input field you want to disable

Submit PHP form does not pass php variable to javascript function

In a php application with I inherited (I am a php newbie) I have a php form with multiple includes. One of the includes has two tables set up and within each table is a form. The first form displays records retrieved from a MySQL database, so there could be 1 or more records returned. A while loop goes through the records and populates the controls with the data for each record (name, phone, email). The controls are named [fieldname<?php echo $line; ?>] - where $line starts at 1 and is incremented as the while loop goes through the records. This is working fine!
The problem comes when someone wants to edit one of the fields and submits the change. The form has an onsubmit="return validateForm(<?php echo $line; ?>);" I have checked to ensure that the $line variable does increment, but when it is sentto the javascript function "validateForm" the variable is not defined in the javasscript function. Originally I did I not pass the $line variable but the javascript function kept telling me that it could not get the value of the undefined element.
FIRST FORM CODE
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
<table border="0" cellspacing="0" cellpadding="0" class="forms">
<col width="20%"/>
<col width="80%"/>
<?php
if($user_access == 'National'){
$result = mysql_query("SELECT * FROM Profile ORDER BY profile_name");
}else{
$result = mysql_query("SELECT * FROM Profile WHERE profile_parent_region = '$user_profile' ORDER BY profile_name");
}
$line = 1;
while ($row_profile = mysql_fetch_array($result)){
$field_id = "_" . $line;
?>
<!-- LINE -->
<tr><td colspan="11"><hr class="view_line"></td></tr>
<!-- LINE -->
<tbody id="region<?php echo $field_id; ?>" >
<input class="field_long" name="profile_id<?php echo $field_id; ?>" id="profile_id<?php echo $field_id; ?>" type="hidden" value="<?php echo $row_profile[profile_id]; ?>"/>
<tr>
<td>
<label class="field_label" for="profile_parent_region<?php echo $field_id; ?>">Profile: </label>
</td>
<td align="left">
<select name="profile_parent_region<?php echo $field_id; ?>" id="profile_parent_region<?php echo $field_id; ?>" class="drop_med" >
<option></option>
<?php
if($user_access != 'National'){
$result_profile = mysql_query("Select Distinct profile_parent_region FROM profile where profile_parent_region = '$user_profile' ");
}else {
$result_profile = mysql_query("Select Distinct profile_parent_region FROM profile ORDER BY profile_parent_region ASC");
}
while($row = mysql_fetch_array($result_profile)){
echo '<option value ="'.$row['profile_parent_region'].'"';
if($row['profile_parent_region'] == $user_profile){
echo ' selected="selected"';
}
echo ' > ' . $row['profile_parent_region'] . '</option>';
}
?>
</select>
<span class="must_fill">* </span>
<label class="form_des" for="profile_parent_region<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td>
<label class="field_label" for="profile_name<?php echo $field_id; ?>">Region: </label>
</td>
<td align="left">
<select name="profile_name<?php echo $field_id; ?>" id="profile_name<?php echo $field_id; ?>" class="drop_med" >
<option></option>
<?php
$parent_region = $row_profile['profile_name'];
if($user_access != 'National'){
$result_region = mysql_query("Select Distinct region FROM regions where parent_region = '$user_profile' ");
}else {
$result_region = mysql_query("Select Distinct region FROM regions ORDER BY region ASC");
}
while($row = mysql_fetch_array($result_region)){
echo '<option value ="'.$row['region'].'"';
if ($row['region'] == $parent_region){
echo ' selected="selected"';
}
echo ' >' . $row['region'] . '</option>';
}
?>
</select>
<span class="must_fill">* </span>
<label class="form_des" for="profile_name<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_manager<?php echo $field_id; ?>" >Region's Manager's Name: </label></td>
<td>
<input class="field_long" name="profile_manager<?php echo $field_id; ?>" id="profile_manager<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_manager]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_manager<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_phone<?php echo $field_id; ?>" >Region's Contact Number: </label></td>
<td>
<input class="field_long" name="profile_phone<?php echo $field_id; ?>" id="profile_phone<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_phone]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_phone<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_email<?php echo $field_id; ?>" >Region's Contact E-mail: </label></td>
<td>
<input class="field_long" name="profile_email<?php echo $field_id; ?>" id="profile_email<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_email]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_email">This email address will also be used to advise of files added to a submitted order.</label>
</td>
</tr>
<tr align="center">
<td colspan="2" class="loginrow">
<br />
<input name="Login <?php echo $field_id; ?>" id="Login<?php echo $field_id; ?>" value="Update Profile" type="submit" class="submit_button"/>
<br />
<br />
</td>
</tr>
</tbody>
<?php
$line++;
}
?>
</table>
</form>`
JAVASCRIPT FUNCTION - location in "parent" php form
function validateForm(lineNum) {
if (lineNum == null) {
var x = document.forms["submit_order"]["file_name"].value;
if (x == null || x == '') {
alert("Missing File Name.");
return false;
}
var x = document.forms["submit_order"]["file_for"].value;
if (x == null || x == '') {
alert("Missing File Type.");
return false;
}
var x = document.forms["submit_order"]["OrderForm"].value;
if (x == null || x == '') {
alert("Missing File to Upload.");
return false;
}
}
Your code
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
is outside the loop of linenumbers - so what should $line be, but null?
You either need to move the form into the loop of linenumbers, generating a form per row, or apply the logic on the submit button in question.
If you go with a form per row, you don't even need the linenumber thingy, cause then there would be exactly one value per variable in the submitted array. This would be the preferable way, cause you don't need to submit all values, when you want to modify one row.
And for the validation itself, you also wouldn't need it, cause you could refer to the form in question.
<?php
$line = 0;
while ($row_profile = mysql_fetch_array($result)){
$field_id = "_" . $line;
?>
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
<!-- do all the row stuff -->
</form>
<?$line++; }?>

Cant get value of hidden field after ajax Jquery

I have a page that when a link is clicked it opens a pop up box to insert new charges. When this pop up box opens I use jquery load() function to insert a table with all the current charges (loaded from mysql) from a script on another page called load_charges.php.
The problem I am having is I can not access any of the hidden values from the content I just loaded I use:
var charge_id = $(':hidden:first', $(this)).val();
this normally gets me the value of the first hidden element but it does not work if I am trying get the info from the page load from load_charges.php. I will list my code below:
case_cpanel.php:
//HTML Table with Form elememt
<table>
<tr class="lead_hover">
<td>
<form class="calc" title="Case Expense Calculator" style="cursor:pointer;">
<input type="hidden" id="lead_id" value="21946295" />
<input type="hidden" id="final_id" value="74" />
<input name="order" type="hidden" id="final_id" value="3" />
</form>
</td>
</tr>
<tr class="lead_hover">
<td>
<form class="calc" title="Case Expense Calculator" style="cursor:pointer;">
<input type="hidden" id="lead_id" value="21978679" />
<input type="hidden" id="final_id" value="79" />
<input name="order" type="hidden" id="final_id" value="1" />
</form>
</td>
</tr>
</table>
// Jquery to load popup form box
$(".calc").click(function () {
var value = $(':hidden:eq(0)', $(this)).val();
$('input[name=lead_id]').val(value);
var value = $(':hidden:eq(1)', $(this)).val();
$('input[name=final_id]').val(value);
var value = $(':hidden:eq(2)', $(this)).val();
$('.order').val(value);
var lead_id = $(':hidden:eq(0)', $(this)).val();
var string1 = "token=<? echo $_SESSION['token']; ?>&lead_id=";
var url = "../ajax/load_charges.php";
var datastring = string1.concat(lead_id);
$('#calc_right_display').html('<div><img src="../imgs/loading4.gif" align="center" /></div>').load(url, datastring).show();
$("#calc_div").overlay().load();
});
load_charges.php:
// table that is load with new form elements
<table width="266" border="0" cellpadding="5">
<? do { ?>
<tr>
<td width="163">
<? echo $row_charges[ 'rows'][ 'title']; ?>
</td>
<td width="83">$
<? echo $row_charges[ 'rows'][ 'charge']; ?>
</td>
<td width="27">
<form class="delete_charge" title="Delete Charge" style="cursor:pointer;">
<input type="hidden" id="id1" value "<? echo $row_charges['rows']['id']; ?>">
</form>
</td>
</tr>
<? } while ($row_charges[ 'rows']=m ysql_fetch_assoc($row_charges[ 'query'])); ?>
</table>
//Jquery Code on load_charges.php
<script>
$(".delete_charge").click(function () { * *
var charge_id = $(':hidden:first', $(this)).val(); * *
var str2 = "token=<? echo $_REQUEST['token']; ?>&delete_charge=true&id=";
var str_lead_id = "&lead_id=<? echo $_REQUEST['lead_id']; ?>";
var url2 = "../ajax/cm_expenses_delete.php";
var datastring2 = str2.concat(charge_id, str_lead_id);
$('#calc_right_display').html('<div><img src="../imgs/loading4.gif" align="center" /></div>').load(url2, datastring2).show();
});
</script>
The problem is var charge_id = $(':hidden:first', $(this)).val(); is not returning any value from the new page that just loaded. Any Help would be greatly appreciated.
Thank you in advance.
Ryan
You may be having a problem retrieving the value because you are missing an equal sign.This:
<input type="hidden" id="id1" value"<? echo $row_charges['rows']['id']; ?>">
Change to:
<input type="hidden" id="id1" value="<? echo $row_charges['rows']['id']; ?>">
This would explain it because your input has no value.
I made the following test, based on your data:
$(document).ready(function(){
var charge_id = $('input:hidden:first').val();
alert(charge_id);
var charge_id = $('input[type=hidden]:first').val();
alert(charge_id);
});
Working fiddle here: http://jsfiddle.net/robertrozas/c4AHM/1/

Ajax oncheck event to search item in a table

modify search
<div class="highlight_2"> <img src="images/collapse2.jpg" width="151" height="28" border="0" />
<div id="inox">
<input type="checkbox" value="kar_kar" />kar and kar <br />
<input type="checkbox" value="bala_bala" />bala and bala <br />
<input type="checkbox" value="jena_jena" />jena and jena <br />
<input type="checkbox" value="senapati" />senapati <br />
<input type="checkbox" value="sarangi_sarangi" />sarangi and sarangi <br />
<input type="checkbox" value="sairam" />sairam <br />
<input type="checkbox" value="madhumita" />madhumita <br />
<div class="clear"></div>
</div>
search table
<tr>
<td>Sl No.</td>
<td>Bus Operator</td>
<td>Bus No. </td>
<td>Departure Time</td>
<td>Arrival time</td>
</tr>
<?php
$count=0;
$s=mysql_query("SELECT * FROM bus_detail where source_point='$_SESSION[source_point]' && destination_point='$_SESSION[destination]'");
while($row=mysql_fetch_array($s))
{
$count+=1;
?>
<tr>
<td><?php echo $count; ?></td>
<td><input name="bus_name" type="text" value="<?php echo $row['bus_name'];?>" class="input_box" /> </td>
<td><?php echo $row['bus_no'];?></td>
<td><?php echo $row['departure_time'];?></td>
<td><?php echo $row['arrival_time'];?></td>
</tr>
<?php }?>
I want to use my modify search in a ajax oncheck event.. In the picture i ve given ,this is my search list apper but if i check a check box name "jena and jena" from the bus operator div, it should only show me the result of jena and jena , the other two, i want to hide them .. I want to modify my search according to my bus operators(after checking a check box from the operator list).. It ll be a great help .. Thank you
My database :
Sorry i miss understood your question. I think you are looking to hide / show html table rows when user selects list. If this is what you are look, Then please check by code below.
Note: You can tweak this code to get better performance and result
Fiddle: http://jsfiddle.net/663Mx/2/
$("#inox input[type='checkbox']").live('click', function () {
// STORE CHECKED VALUED IN ARRAY
var cv = [];
$("#inox input[type='checkbox']:checked").each(function () {
cv.push($(this).val());
});
// SHOW / HIDE ROWS BY DEFAULT
if(cv.length <= 0) {
$("#mytab tbody").find("tr").show();
} else {
$("#mytab tbody").find("tr").hide();
var rows = $("#mytab tbody").find("tr");
var data = $(this).val();
// LOOP THROUGH AND SHOW ONLY CHECKED ROWS
rows.each(function (i, v) {
for (var n=0; n<cv.length; n++) {
var check = $(v).find('td').filter(":contains('" + cv[n] + "')");
check.parent('tr').show();
}
});
}
});

Javascript + PHP - How to check a checkbox when user select a file to upload

I have an input file list from database:
<?php
for ($x=0; $x<count($Permisos); $x++) {
?>
<tr>
<td> <?php echo utf8_encode($Permisos[$x]['des_permiso']); ?></td>
<td> <input name="txt_arch_<? echo $x;?>" type="file" class="text" id="txt_arch_<? echo $x;?>"> </td>
<td> <input name="cbx_<? echo $x;?>" type="checkbox" class="text" id="cbx_<? echo $x;?>" value="S">
</td>
</tr>
<?php
}
?>
This code returns a list of 'permisos' (requirements) with a checkbox next, for check it to upload the file.
What i have to do is: when user select a file (id or name: "txt_arch_<? echo $x;?>"), the checkbox ("cbx_<? echo $x;?>") will check it automatically.
I don't know if if explain very well.
Thank you for answers.
Add this to the document.ready event, assuming your using the jQuery framework:
$('input[type="file"]').on('change',
function()
{
$(this).next('input[type="checkbox"]').prop('checked', true);
}
);
I solved it:
// .....
<input onChange="VerifyFctn('<?php echo $x; ?>')" name="txt_arch_<? echo $x;?>" type="file" class="text" id="txt_arch_<? echo $x;?>">
// .....
Javascript:
function VerifyFctn(id){
document.getElementById("cbx_"+id).checked = true;
}
Anyway, thank you for see the post :)
Greetings

Categories